JAVA------TCP send data and receive data

TCP send data and receive data

1. TCP communication principle :

  • The TCP communication protocol is a reliable network protocol. It establishes a Socket object at both ends of the communication, thereby forming a network virtual link at both ends of the communication. Once the virtual network link is established, the programs at both ends can pass Virtual link for communication

  • Java provides a good package for the network based on the TCP protocol, using Socket objects to represent the communication ports at both ends, and generating IO streams through Socket for network communication. Java provides the Socket class for the client and the ServerSocket class for the server.

  • Insert picture description here


2. The steps of TCP sending data:

  1. Create the client's Socket object (Socket)
  2. Get output stream, write data
  3. Release resources

Look at the code demo:

send data:

package TCP;

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

public class SendDemo {
    
    
	public static void main(String[] args) throws IOException{
    
    
		//创建客户端的Socket对象
		//Socket (InetAddress adress,int port)创建流套接字并将其连接到指定IP地址的指定端口号
//		Socket s=new Socket(InetAddress.getByName("192.168.224.1"), 10000);
		//Socket (String host,int port)创建流套接字并将其连接到指定主机的指定端口号
		Socket s=new Socket("192.168.223.1", 10000);
		
		//获取输出流,写数据
		//OutputStream getOutputStream();返回此套接字的输出流
		OutputStream os=s.getOutputStream();
		os.write("hello,tcp".getBytes());
		
		//释放资源
		s.close();
		
	}

}

Because TCP is a reliable transmission, there must be a three-way handshake, so the data sending program can be used normally only when the data receiving program is running. Here 192.168.223.1 is the IP address of the machine.


3. The steps of TCP receiving data:

  1. Create the client's Socket object (SevereSocket)
  2. Get the input stream, read the data, and display the data on the console
  3. Release resources

Look at the code demo:

package TCP;

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

public class ReceiveDemo {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//创建客户端的Socket对象(SevereSocket)
		//ServerSocket (int port)创建绑定到指定端口的服务器套接字
		ServerSocket ss=new ServerSocket(10000);	
		
		//Socket accept()侦听要连接到此套接字并接受他
		Socket s=ss.accept();
		
		//获取输入流,读数据,并把数据显示在控制台
		InputStream is=s.getInputStream();
		byte[] bys=new byte[1024];
		int len=is.read(bys);
		String data=new String(bys,0,len);
		System.out.println("数据是:"+data);
			
		//释放资源
		s.close();
		ss.close();	
	}

}

The final receiving end output: "Data is: hello, tcp"

Guess you like

Origin blog.csdn.net/weixin_45102820/article/details/113781072