java-simulate server and client for tcp communication

TCP communication

Insert picture description here

Insert picture description here

Problem solving ideas

  1. First of all, it must be the server start, because our users may access the server at any time, so the server needs to be started all the time, waiting to be accessed.
  2. Then the client sends a message to the server, then the client is the output stream, and then writes the message; the server is the input stream, and reads the message in.
  3. The above has completed a communication, then the server will be used as the output stream to write out the message and send it to the client; the client is the input stream and read the message in.
  4. The above operation completes a two-way communication. Then this process is given an endless loop, then the server and the client can always maintain stable communication. (This step will not be written)

Upload code

Client. All exceptions are thrown away, which is convenient to straighten out the idea, but development is best not to do this. Remember

public class User {
    
    

	public static void main(String[] args) throws UnknownHostException, IOException {
    
    
				//1.创建Socket,用来发送请求
				Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8991); 
				// 前面个参数是传入127.0.0.1这个地址的主机是自己的主机,后面是自己的端口号这个随便写最好写8000以上的,客户端和服务端的端口号一定要相同
				
				//创建输出流
				DataOutputStream dos = new DataOutputStream( socket.getOutputStream());
				DataInputStream dis = new DataInputStream( socket.getInputStream());
				//发送数据
				String info = "我是客户端";
				dos.writeUTF(info); //writeUTF(String) 这个就是写字符串,DataOutputStream这个可以操作基本数据类型和String,
				
				//接受服务端发送的消息
				String str = dis.readUTF();
				System.out.println("我客户端已收到消息: " + str);
				//关闭流以及socket
				dos.close();
				dis.close();
				socket.close();
		
	}
}

On the server side, just throw the biggest exception directly, hahaha, one dish

public class Server {
    
    
	public static void main(String[] args) throws Exception {
    
    
		//1.创建一个ServerSocket,指定等待端口
		ServerSocket serverSocket = new ServerSocket(8991);
		//2.使用ServerSocket接收用户的请求(处于监听状态)
		Socket socket = serverSocket.accept();
		//3.创建输入流和输出流
		DataInputStream dis = new DataInputStream( socket.getInputStream());
		DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
		//4.接收用户数据并输出
		String str = dis.readUTF(); //读取字符串
		System.out.println("服务端已收到消息:" + str);
		//5.发送反馈信息,给客户端发送表示已接受的消息
		String s = "我服务端已收到您的消息";
		dos.writeUTF(s);
		//6.关闭流和socket
		dis.close();
		dos.close();
		socket.close();
		serverSocket.close();
		
	}
}

Then start the server first, and then start the client.
Get the correct result.
The server side and the
Insert picture description here
client side
Insert picture description here
have completed a duplex communication.

Guess you like

Origin blog.csdn.net/toomemetoo/article/details/112910194