Java provides two classes for the TCP protocol, which are used in client programming and server-side programming, respectively. Before the application begins to communicate, you need to create a connection that is initiated by the client program, and the server-side program needs to listen to the host's specific port number and wait for the client to connect. In the client we only need to use the socket instance, while the server side handles both the ServerSocket instance and the socket instance, both of which use OutputStream and Inpustream to send and receive data.
The best way to learn a knowledge is to use it, through the previous notes, we already know how to get the host address information, and now we have a simple program to learn the transport layer using the TCP protocol socket programming.
TCP Server Side
In socket programming, the server side is far more complex than the client. Server-side work is to establish a communication terminal, passively waiting for the client to connect. The following example of a server-side program is to listen for the port number entered from the console and send the message back to the client.
Copy Code code as follows:
importjava.net.*;
Importjava.text.MessageFormat;
importjava.io.*;
publicclasstcpechoserver{
privatestaticfinalintbufsize=32;
Publicstaticvoidmain (String[]args) throwsioexception{
Todoauto-generatedmethodstub
Get the port number you want to listen to from the console
if (args.length!=1)
Thrownewillegalargumentexception ("Parameter (s):<port>");
Get Port number
Intservport=integer.parseint (Args[0]);
Instantiating an instance of a ServerSocket object
Serversocketservsocket=newserversocket (Servport);
System.out.println (Messageformat.format ("Start listening, port number: {0}", Args[0]);
Total number of bytes initially received data
Intrecvmsgsize;
Buffer to receive data
Byte[]receivebuf=newbyte[bufsize];
Loop iterations, listening for port numbers, handling new connection requests
while (true) {
Block wait, create a new connection instance every request is received
Socketclntsocket=servsocket.accept ();
Gets the socketaddress of the connected client
Socketaddressclientaddress=clntsocket.getremotesocketaddress ();
Print Output connection client address information
System.out.println ("Handlingclientat" +clientaddress);
Objects that receive data from the client
Inputstreamin=clntsocket.getinputstream ();
An object that sends data to the client
Outputstreamout=clntsocket.getoutputstream ();
After reading the data sent by the client, then sending it to the client
while ((Recvmsgsize=in.read (RECEIVEBUF))!=-1) {
Out.write (receivebuf,0,recvmsgsize);
}
Close the connection when the client closes the connection
SYSTEM.OUT.PRINTLN ("Client close connection");
Clntsocket.close ();
}
}
}
TCP Client
In socket programming, first the client needs to send to the server side and then passively wait for the server-side response. In the following example: We send information to the server side, wait for the message to be sent by the server, and print it out.
Copy Code code as follows:
importjava.io.*;
Importjava.net.Socket;
Importjava.net.SocketException;
publicclasstcpechoclient{
Publicstaticvoidmain (String[]args) throwsioexception{
Todoauto-generatedmethodstub
Determine if the parameters accepted 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 you need to send
Byte[]data=args[1].getbytes ();
If there are three port numbers from which to send information, the default port number is 8099
Intservport= (args.length==3)? Integer.parseint (args[2]): 8099;
Instantiate an instance of a socket based on the server address and port number
Socketsocket=newsocket (Server,servport);
System.out.println ("connectedtoserver...sendingechostring");
Returns the input stream for this socket, which is the data object accepted from the server
Inputstreamin=socket.getinputstream ();
Returns the output stream for this socket, which is the data object sent to the server
Outputstreamout=socket.getoutputstream ();
Send data received from the console to the server
Out.write (data);
The counter that receives the data, the initial offset to which the data is written
Inttotalbytesrcvd=0;
The total number of bytes initialized to receive data
INTBYTESRCVD;
while (Totalbytesrcvd<data.length) {
The server closes the connection, returns the total number of bytes received by the -1,read method
if (Bytesrcvd=in.read (data,totalbytesrcvd,data.length
-TOTALBYTESRCVD)) ==-1)
Thrownewsocketexception ("Connection to server is off");
TOTALBYTESRCVD+=BYTESRCVD;
}
Data sent by the print server
System.out.println ("Received:" +newstring (data));
Close connection
Socket.close ();
}
}
First run the server side and listen for Port 8099:
Then run the client program and send a message to the server side:
Looking at our server-side console again, we can see the address information for the previous client connection: