1. TCP send data steps
TCP发送数据的步骤:
1.创建客户端的Socket对象
2.获取输出流,写数据
3.释放资源
2. Send data program code
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class ClientDemo {
public static void main(String[] args) throws IOException {
//1.创建客户端的Socket对象
//Socket(String host, int port) 创建流套接字并将其连接到指定主机上的指定端口号。
Socket s = new Socket("zshao",10001);
//2.获取输出流,写数据
//OutputStream getOutputStream() 返回此套接字的输出流。
OutputStream os = s.getOutputStream();
os.write("hello,tpc".getBytes());
//3.释放资源
s.close();
}
}
3. TCP receive data steps
TCP接收数据的步骤
1.创建服务器端的Socket对象
2.监听客户端的连接,返回一个Socket对象
3.获取输入流,读数据,并把数据显示在控制台上
4.释放资源
4. Receive data code
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
public static void main(String[] args) throws IOException {
//1.创建服务器端的Socket对象
//ServerSocket(int port) 创建绑定到指定端口的服务器套接字。
ServerSocket ss = new ServerSocket(10001);
//2.监听客户端的连接,返回一个Socket对象
//Socket accept() 侦听要连接到此套接字并接受它。
Socket s = ss.accept();
//3.获取输入流,读数据,并把数据显示在控制台上
InputStream is = s.getInputStream();
byte [] bys = new byte[1024];
int len;
while ((len=is.read(bys))!=-1){
System.out.println("数据是:"+ new String(bys,0,len));
}
//4.释放资源
ss.close();
}
}
5. Program running results
First open the running receiving program to wait for sending, and then run the sending program, the result is shown as follows:
6. Visualize memory
To facilitate memory, I thought of a metaphor.
Assume that TCP communication is the communication between two cities in ancient times.
Sender to send messengers to send information, so we must first create a messenger ( the Socket ) objects, messenger to know exactly to what cities ( IP ) of which door ( Port ), then the messenger carrying information out of the city ( OutputStream ), a finish to Close the city gate ( close ).
The recipient is another city. First open the corresponding door ( ServerSocket ), the person who receives the letter from the door ( Socket s = ss.accept() ), then accept the message ( InputStream ), and finally close the city gate ( close ).