Socket network programming example of server and client

  • 2020-04-01 02:50:56
  • OfStack

Java provides two classes for the TCP protocol, which are used in both client-side and server-side programming. Before the application can start communicating, a connection needs to be created and initiated by the client program. The server-side program needs to always listen for a specific port number of the host, waiting for the client to connect. In the client side, we only need to use the Socket instance, while the server side needs to handle both the ServerSocket instance and Socket instance. Both also use OutputStream and InpuStream to send and receive data.

The best way to learn something is to use it. From the previous notes, we have learned how to get the address information of the host.

TCP server side

In Socket programming, the server side is far more complex than the client side. The server-side job is to set up a communication terminal and passively wait for the client to connect. The following example of a server-side program listens for the port number retrieved from the console input and sends messages from the client back.


importjava.net.*;
importjava.text.MessageFormat;
importjava.io.*;
publicclassTCPEchoServer{
privatestaticfinalintBUFSIZE=32;
publicstaticvoidmain(String[]args)throwsIOException{
//TODOAuto-generatedmethodstub
    //Gets the port number from the console to listen for
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 monitoring, port number :{0}",args[0]));
//The total number of bytes of data initially received
intrecvMsgSize;
//The buffer that receives the data
byte[]receiveBuf=newbyte[BUFSIZE];
//Loop over, listen for port Numbers, and process new connection requests
while(true){
//Blocks the wait, creating a new connection instance for each request received
SocketclntSocket=servSocket.accept();
//Gets the SocketAddress of the connected client
SocketAddressclientAddress=clntSocket.getRemoteSocketAddress();
//Print out the connection client address information
System.out.println("Handlingclientat"+clientAddress);
//An object that receives data from a client
InputStreamin=clntSocket.getInputStream();
//An object that sends data to a client
OutputStreamout=clntSocket.getOutputStream();
//After reading the data sent by the client, it is sent 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(" The client closes the connection ");
clntSocket.close();
}
}
}


TCP client

In Socket programming, the client first needs to send to the server, and then passively waits for the response from the server. In the following example, we send a message to the server side, wait for the message to be sent from the server side, and print it out for display.


importjava.io.*;
importjava.net.Socket;
importjava.net.SocketException;
publicclassTCPEchoClient{
publicstaticvoidmain(String[]args)throwsIOException{
//TODOAuto-generatedmethodstub
    //Determines whether the parameters received from the console are correct
if((args.length<2)||(args.length>3))
thrownewIllegalArgumentException(
"Parameter(s):<Server><Word>[<Port>]]");
//Get the server address
Stringserver=args[0];
//Get the information you need to send
byte[]data=args[1].getBytes();
//If there are three slave parameters, get the port number to send the message. 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");
//Returns the input stream for this socket, which is the data object received from the server
InputStreamin=socket.getInputStream();
//Returns the output stream of this socket, which is the data object sent to the server
OutputStreamout=socket.getOutputStream();
//Sends data received from the console to the server
out.write(data);
//The counter that receives the data will write the initial offset of the data
inttotalBytesRcvd=0;
//Initializes the total number of bytes of received data
intbytesRcvd;
while(totalBytesRcvd<data.length){
//When the server closes the connection, -1 is returned, and 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 was 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 side and listen to port 8099:
< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201401/20140122163143.jpg? 2014022163310 ">

Then run the client program and send a message to the server:
< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201401/20140122163202.jpg? 2014022163324 ">

Looking again at our server-side console, we can see the address information of the previous client connection:
< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201401/20140122163217.jpg? 2014022163343 ">


Related articles: