1,TCP通信的流程:
2,TCP的通信的程序组成及步骤:
A,服务端(先有输入): ServerSocket
1. 创建服务器端对象:
ServerSocket serverSocket = new ServerSocket(8083);
2. 同意客户端请求:
Socket socket = serverSocket.accept();
3. 创建输入流读取由客户端输入的数据:
InputStream inputStream = socket.getInputStream();
//新建一个空数据包接受数据:
byte[] bytes = new byte[1024];
//读取数据长度:
int length = inputStream.read(bytes);
System.out.println(new String(bytes,0,length));
4. 创建输出流向客户端输出数据:
OutputStream outputStream = socket.getOutputStream();
outputStream.write("da".getBytes());
5. 关闭:
//关闭:
outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
B,客户端: Socket
6. 创建客户端对象:
//服务器端ip和端口:
Socket socket = new Socket("127.0.0.1", 8083);
7. 创建输出流向服务端输出数据:
OutputStream outputStream = socket.getOutputStream();
//getBytes:字符串转字节;
outputStream.write("nnn".getBytes());
8. 创建输入流读取服务端输入的数据:
InputStream inputStream = socket.getInputStream();
//新建一个空数据包:(接收数据)
byte[] bytes = new byte[1024];
//获取数据长度;
int len = inputStream.read(bytes);
System.out.println(new String(bytes,0,len));
9. 关闭:
outputStream.close();
inputStream.close();
socket.close();