Java provides two classes for the TCP protocol, which are used in client-side programming and server-side programming respectively. Before the application starts communication, a connection needs to be created first, initiated by the client program; and the server-side program needs to always listen to the specific port number of the host, waiting for the client's connection. In the client, we only need to use Socket instances, while the server needs to handle both ServerSocket instances and Socket instances; both use OutputStream and InpuStream to send and receive data.
The best way to learn a piece of knowledge is to use it. Through the previous notes, we already know how to obtain the address information of the host. Now we use a simple program to initially learn Socket programming using the TCP protocol in the transport layer.
TCP server side
In Socket programming, the server side is much more complicated than the client side. The job of the server is to establish a communication terminal and passively wait for the client's connection. The following example of a server-side program is used to listen to the port number obtained from the console input, and send the message sent by the client back.
Copy the code code as follows:
importjava.net.*;
importjava.text.MessageFormat;
importjava.io.*;
publicclassTCPEchoServer{
privatestaticfinalintBUFSIZE=32;
publicstaticvoidmain(String[]args)throwsIOException{
//TODOAuto-generatedmethodstub
//Get the port number to be monitored from the console
if(args.length!=1)
thrownewIllegalArgumentException("Parameter(s):<Port>");
//Get the port number
intservPort=Integer.parseInt(args[0]);
//Instantiate a ServerSocket object instance
ServerSocketservSocket=newServerSocket(servPort);
System.out.println(MessageFormat.format("Start listening, port number: {0}",args[0]));
//Total number of bytes of initial received data
intrecvMsgSize;
//buffer for receiving data
byte[]receiveBuf=newbyte[BUFSIZE];
//Loop iteration, listen to the port number, and process new connection requests
while(true){
//Block and wait, create a new connection instance every time a request is received
SocketclntSocket=servSocket.accept();
//Get the SocketAddress of the connected client
SocketAddressclientAddress=clntSocket.getRemoteSocketAddress();
//Print out the connection client address information
System.out.println("Handlingclientat"+clientAddress);
//Object that receives data from the client
InputStreamin=clntSocket.getInputStream();
//Object that sends data to the client
OutputStreamout=clntSocket.getOutputStream();
//After reading the data sent by the client, send it to the client
while((recvMsgSize=in.read(receiveBuf))!=-1){
out.write(receiveBuf,0,recvMsgSize);
}
//When the client closes the connection, close the connection
System.out.println("Client closes connection");
clntSocket.close();
}
}
}
TCP client
In Socket programming, first the client needs to send to the server, and then passively wait for the server's response. In the following example: we send information to the server, wait for the message sent by the server, and print it out.
Copy the code code as follows:
importjava.io.*;
importjava.net.Socket;
importjava.net.SocketException;
publicclassTCPEchoClient{
publicstaticvoidmain(String[]args)throwsIOException{
//TODOAuto-generatedmethodstub
//Determine whether the parameters received from the console are correct
if((args.length<2)||(args.length>3))
thrownewIllegalArgumentException(
"Parameter(s):<Server><Word>[<Port>]]");
//Get server address
Stringserver=args[0];
//Get the information that needs to be sent
byte[]data=args[1].getBytes();
//If there are three slave parameters, get the port number for sending information. The default port number is 8099.
intservPort=(args.length==3)?Integer.parseInt(args[2]):8099;
//Instantiate a Socket instance based on the server address and port number
Socketsocket=newSocket(server,servPort);
System.out.println("Connectedtoserver...sendingechostring");
//Return the input stream of this socket, which is the data object received from the server
InputStreamin=socket.getInputStream();
//Return the output stream of this socket, which is the data object sent to the server
OutputStreamout=socket.getOutputStream();
//Send the data received from the console to the server
out.write(data);
//The counter that receives data will write the initial offset of the data
inttotalBytesRcvd=0;
//Initialize the total number of bytes of received data
intbytesRcvd;
while(totalBytesRcvd<data.length){
//If the server closes the connection, it returns -1. The read method returns the total number of bytes of received data.
if((bytesRcvd=in.read(data,totalBytesRcvd,data.length
-totalBytesRcvd))==-1)
thrownewSocketException("The connection to the server has been closed");
totalBytesRcvd+=bytesRcvd;
}
//Print the data sent by the server
System.out.println("Received:"+newString(data));
//Close the connection
socket.close();
}
}
First run the server and listen on port 8099:
Then run the client program and send a message to the server:
Looking at our server-side console again, we can see the address information of the previous client connection: