Java realizes network communication (TCP programming)


Tip: The following is the content of this article, the following cases are for reference

1. What is TCP network programming?


TCP network programming refers to the use of Socket class to write communication programs.
The programs that use the TCP protocol to communicate are primary and secondary, one is called the server-side program, and the other is called the client-side program


2. Principles of TCP network programming:

1. Icon:

Insert picture description here

2. Client-side and server-side analysis:

The essence of Socket is to abstract data into I/O streams and transmit data
sockets between networks : the endpoint of communication between two machines

Server side : can write data to the client, read the data sent by the
client client : can read the data sent by the server, write data to the server

Tools used:
Server side: ServerSocket
Create object : ServerSocket(int port)
This method creates a server socket bound to a specific port. The
parameter port is the port number , which is defined by yourself, divided by 0~1024 and the installed software is occupied by default Port number other than the port number
calling method : Socket (return value type) accept()
This method listens and receives the connection of this socket

Client: Socket
creation object : Socket(String host,int port) The
parameter host is the IP address , and port is the port number.
This method creates a stream socket and connects it to the port number on the specified host.
Calling method : InputStream class The getInputStream() method
This method can return the input stream of this socket
                  The getOutputStream() method in
the OutputStream class This method can return the output stream of this socket

3. How to use DOS window to check your own IP address:

①Open the cmd administrator window

Press the win+r key to quickly launch the command window, enter cmd to open the administrator interface
Insert picture description here
Insert picture description here

②Enter the command to view the IP address

Enter the ipconfig command to get the address information of the machine, and IPv4 is the IP address of the machine
Insert picture description here


3. Network communication case test:

1. Server-side class:

package dreamfly.net.server;

//读取客户端发来的数据,给客户端写出数据

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    
    

    public static void main(String[] args) throws IOException {
    
    

        //1.开启服务器,参数是指开着的端口号
        ServerSocket server = new ServerSocket(8899);
        System.out.println("服务器已成功启动");
        //2.接收客户端发来的连接
        Socket socket = server.accept();
        System.out.println("接收到客户端发来的请求");
        //3.获取读取流
        InputStream in = socket.getInputStream();
        //4.读取数据
//        int data = in.read();      //默认返回的是整数
        for (int i = 0;i < 5;i++){
    
    
            char data = (char)in.read();
            System.out.print(data);
        }
        //5.给客户端写出数据
        System.out.println();
        OutputStream out = socket.getOutputStream();
        out.write("world".getBytes());
        System.out.println("服务器端成功发送数据");
        out.close();
    }
}

To run when first thrown at IOException method or use try / catch statement block surrounded statement exception may occur , where I chose the first throw IOException, followed by output statements in the server-side class is to detect whether success Send out the data . If the output statement is not executed, it means that the data has not been sent successfully.

2. Client class:

package dreamfly.net.client;

//读取服务器端发来的数据,给服务器端写出数据

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Client {
    
    

    public static void main(String[] args) throws IOException {
    
    
        //1.连接到指定的服务器(ip+port)
        Socket socket = new Socket("127.0.0.1",8899);
        System.out.println("已连接成功");
        //2.获取写出流
        OutputStream out = socket.getOutputStream();
        //3.写出数据,字节流只能写出整数或字节数组
        //将hello对应整数编程对应的字节数组,getBytes()将String转换为byte[]
        out.write("hello".getBytes());
        System.out.println("客户端成功发送数据");
        InputStream in = socket.getInputStream();
        for (int i = 0;i < 5;i++){
    
    
            char data = (char)in.read();
            System.out.print(data);
        }
        System.out.println();
        System.out.println("成功接收服务器端数据");
        out.close();
    }
}

4. Operation results:

1. Turn on the server

Insert picture description here

2. Open the client

Server-side running results:
Insert picture description here

Client running results:
Insert picture description here

3. Matters needing attention:

The order of operation is: first open the server and then run the client.
OutStream byte stream can only write integers or byte arrays . To transmit string data, use the getBytes() method to convert String data to byte[] Byte array

If the client is turned on without the server, it will have the following operating results:
Insert picture description here
Reason: Because the server port number is not opened, the client cannot connect to the corresponding port of the server


Five, summary

The above is the content of simple network communication in Java, and the description of the classes used in this article in the API is attached.
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_48455576/article/details/113197775