Java from entry to the master Chapter 19 Network Communications

Network programming foundation

  • TCP / IP protocol, there are two protocols: TCP, UDP
  • Ports and Sockets
    • Port: 0-65535, connected through different ports of different services, HTTP80, FTP21,
    • Socket: port used to connect the application, similar to the receptacle connector and electrical wires

TCP programming foundation

java.net.InetAdress class, associated with the IP address classes, methods InetAdress class will throw UnknownHostException, so the need for exception handling

java.net.ServerSocket class for representing a server socket

UDP program design

java.net.DatagramPacket class represents packet, java.net.DatagramSocket class represents sockets to send and receive data packets

 

package ex19_Net;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAdress_test {
    public static void main(String args[]) {
        InetAddress ip;
        try {
            ip = InetAddress.getLocalHost();
            String localname = ip.getHostName();
            String localip = ip.getHostAddress();
            System.out.println("name: " + localname);
            System.out.println("ip: " + localip);


        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }


}

 

package ex19_Net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TCP_test {
    private BufferedReader reader;
    private ServerSocket server;
    private Socket socket;
    void getserver() {
        try {
            server = new ServerSocket(8998);
            System.out.println("服务器套接字创建成功");
            while (true) {
                System.out.println("等待客户机的连接");
                socket = server.accept();
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                getClientMessage();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getClientMessage() {
        try {
            while (true) {
                System.out.println("客户机:" + reader.readLine());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if (reader != null) {
                reader.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        TCP_test tcp = new TCP_test();
        tcp.getserver();
    }

}

 

package ex19_Net;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.net.Socket;

public class TCP_test_client extends JFrame {
    private PrintWriter writer;
    Socket socket;
    private JTextArea ta = new JTextArea();
    private JTextField tf = new JTextField();
    Container cc;
    public TCP_test_client(String title) {
        super(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        cc = this.getContentPane();
        final JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBorder(new BevelBorder(BevelBorder.RAISED));
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        scrollPane.setViewportView(ta);
        cc.add(tf,"South");
        tf.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                writer.println(tf.getText());
                ta.append(tf.getText() + '\n');
                ta.setSelectionEnd(ta.getText().length());
                tf.setText("");
            }
        });
    }

    private void connect() {
        ta.append("尝试连接\n");
        try {
            socket = new Socket("127.0.0.1",8998);
            writer = new PrintWriter(socket.getOutputStream(),true);
            ta.append("完成连接\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        TCP_test_client client = new TCP_test_client("向服务器发生数据");
        client.setSize(200,200);
        client.setVisible(true);
        client.connect();
    }
}

 

 

 

 

 

 

 

Published 46 original articles · won praise 0 · Views 1016

Guess you like

Origin blog.csdn.net/weixin_37680513/article/details/104968370