Java Socket network communication

There are four types of network-related classes in Java: InetAddress (network information identification), URL (uniform resource locator, reading and writing network data), Sockets (using TCP / IP for network communication), Datagram (UDP datagram communication)

InetAddress and URL

You can get computer name, IP address and other information through InetAddress

    public static void main(String[] args) throws UnknownHostException {
        InetAddress address=InetAddress.getLocalHost();         // 通过静态方法生成InetAddress实例
        System.out.println("计算机名称:"+ address.getHostName());
        System.out.println("IP地址:"+ address.getHostAddress());
        byte[] ipBytes=address.getAddress();                // 以数组的形式获取IP
        System.out.println("IP地址数组:"+ Arrays.toString(ipBytes));
        System.out.println(address);        //打印实例,输出:主机名/IP

        InetAddress address1=InetAddress.getByName("DELL-T");     // 通过主机名获取实例
        System.out.println(address1.getHostAddress());
        InetAddress address2=InetAddress.getByName("192.168.80.1");     //通过IP字符串获取实例
        System.out.println(address2.getHostName());
    }

url is used to uniquely identify the resource location on the network, and consists of two parts: the protocol name and the resource name, for example, https://www.baidu.com/s?wd=Java#p1, https is the protocol name, followed by the resource name. The URL class in the java.net package is used to manipulate url-related information, which is used as follows:

        URL baidu = new URL("https://www.baidu.com");     // 通过网址创建url实例
        URL url = new URL(baidu, "s?wd=Java#p1");          // 在url对象的基础上拼接成新的url实例

        //查看url相关信息
        System.out.println("协议" + url.getProtocol());
        System.out.println("主机" + url.getHost());
        System.out.println("端口" + url.getPort());
        System.out.println("文件路径" + url.getFile());
        System.out.println("相对路径" + url.getRef());
        System.out.println("查询内容" + url.getQuery());

The results are as follows:

The openStream () method of the url can be used to obtain the network resource corresponding to the url, and the content of the url can be read after the input stream is opened

        InputStream inputStream = url.openStream();    //打开网络资源输入流   
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));   //缓冲读取内容
        String line = br.readLine();
        while (line != null) {
            System.out.println(line);
            line = br.readLine();
        }
        br.close();
        inputStream.close();

Socket communication

Sockets refers to the connection-oriented, reliable, ordered, and byte-oriented network communication class implemented on the basis of the TCP protocol. It mainly includes two classes, the ServerSocket class on the server side and the Socket class on the client side. The communication process is as follows Show

As shown below, the client sends a login request to the server, and the server returns the corresponding Socket communication example process:

//服务器端,先启动
public class ServerSocketDemo {
    public static void main(String[] args) {
        try {
            //1、创建服务器端ServerSocket对象,绑定监听的端口号6666
            ServerSocket serverSocket = new ServerSocket(6666);
            //2、调用accept()方法监听开始,等待客户端连接
            System.out.println("服务器端等待客户端连接。。。");
            Socket socket = serverSocket.accept();
            //3、通过输入流读取客户端传来的信息
            InputStream inputStream = socket.getInputStream();        //获取字节输入流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));//包装为缓冲字符流
            String info;
            while ((info = bufferedReader.readLine()) != null)
                System.out.println("收到客户端信息:" + info);
            InetAddress address = socket.getInetAddress();    // 获取客户端的InetAddress信息
            System.out.println("当前客户端的IP:" + address.getHostAddress());
            socket.shutdownInput();                                 //关闭socket输入流
            //4、通过输出流向客户端返回相应信息
            OutputStream outputStream = socket.getOutputStream();     //获取输出流
            PrintWriter printWriter = new PrintWriter(outputStream);  //将输出流包装为打印流
            printWriter.write("欢迎登录!");
            printWriter.flush();
            socket.shutdownOutput();                                //关闭socket输出流
            //5、关闭资源流
            printWriter.close();
            outputStream.close();
            bufferedReader.close();
            inputStream.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//客户端
public class ClientSocketDemo {
    public static void main(String[] args) {
        try {
            //1、创建客户端Socket对象,指定要连接的服务器和端口
            Socket socket = new Socket("localhost", 6666);
            //2、通过输出流向服务器发送信息
            OutputStream outputStream = socket.getOutputStream();     //获取输出流
            PrintWriter printWriter = new PrintWriter(outputStream);  //将输出流包装为打印流
            printWriter.write("用户名:小明;密码:1234");
            printWriter.flush();
            socket.shutdownOutput();
            //3、通过输入流接收服务器的返回信息
            InputStream inputStream = socket.getInputStream();        //获取字节输入流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));//包装为缓冲字符流
            String info;
            while ((info = bufferedReader.readLine()) != null)
                System.out.println("收到服务器端相应:" + info);
            socket.shutdownInput();
            //4、关闭流资源
            bufferedReader.close();
            inputStream.close();
            printWriter.close();
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

UDP communication

UDP is a connectionless, unreliable, and out-of-order transmission protocol, but its transmission speed is relatively fast, so it is often used in transmission processes that are speed-sensitive and do not require a high rate of accuracy. During transmission, first encapsulate the data to be transmitted into a datagram (Datagram), define the host and port number (Socket) of the data in the datagram, and then send the data out. The DatagramPacket class in Java represents data packets, and the DatagramSocket class represents end-to-end UDP communication. The process of server and client communication via UDP is as follows:

//服务器端
public class UDPServer {
    public static void main(String[] args) throws IOException {
        //服务器端接收客户端信息
        //1、创建非服务器端的UDPsocket对象并指定端口
        DatagramSocket socket = new DatagramSocket(6666);
        //2、创建用于接受客户端数据的数据报
        byte[] data = new byte[1024];            //用于接收数据的字节数组
        DatagramPacket packet = new DatagramPacket(data, data.length);
        //3、接收客户端的数据
        System.out.println("等待客户端数据中。。。");
        socket.receive(packet);
        //4、读取接收在data中的字节数组转化为字符串
        String s = new String(data, 0, packet.getLength());
        System.out.println("服务器端收到的数据:" + s);

        //服务器向客户端发送响应信息
        //1、定义响应信息与客户端的地址和端口
        byte[] response = "欢迎您!".getBytes();
        InetAddress clientAddress = packet.getAddress();  //从客户端发来的数据报中得到其IP地址
        int port = packet.getPort();
        //2、创建响应数据报
        DatagramPacket responsePacket = new DatagramPacket(response, response.length, clientAddress, port);
        //3、发送数据报
        socket.send(responsePacket);
        //4、关闭资源
        socket.close();
    }
}
//客户端
public class UDPClient {
    public static void main(String[] args) throws IOException {
        //客户端向服务器发送数据报
        //1、创建数据报,包含要发送的数据、目标服务器地址、端口号
        byte[] data = "用户名:小明;密码:1234".getBytes();
        InetAddress address = InetAddress.getByName("localhost");
        DatagramPacket packet = new DatagramPacket(data, data.length, address, 6666);
        //2、创建DatagramSocket对象
        DatagramSocket socket = new DatagramSocket();
        //3、发送数据包
        socket.send(packet);

        //客户端接收服务器响应数据报
        //1、创建接收数据报的packet
        byte[] resData = new byte[1024];
        DatagramPacket resPacket = new DatagramPacket(resData, resData.length);
        //2、接收响应数据
        socket.receive(resPacket);
        //3、读取响应数据
        String res = new String(resData, 0, resPacket.getLength());
        System.out.println("客户端收到响应:" + res);
        //4、关闭资源
        socket.close();
    }
}

 

Published 124 original articles · Like 65 · Visit 130,000+

Guess you like

Origin blog.csdn.net/theVicTory/article/details/104189552