Example of a simple server side client application for Java network programming

  • 2020-04-01 03:48:41
  • OfStack

This article illustrates a simple server-side client application for Java network programming. Share with you for your reference. The details are as follows:

In Java, we use java.net.Socket and its associated classes to perform network-related functions. The Socket class is very simple to use because Java technology hides the complex process of establishing network connections and sending data over them. What follows applies only to the TCP protocol.

Connect to the server

We can use the constructor of the Socket class to open a Socket, such as


Socket sk = new Socket("210.0.235.14",13);

Where, 210.0.235.14 is a String object in decimal point, representing the IP address (or hostname) of the destination host, and 13 represents the port 13 on which to connect to the destination host. Here, 210.0.235.14 is a timing server located in Hong Kong. The default port of timing server is generally 13.
Note that the program blocks before successfully connecting to the server.
Next, we can use the getInputStream() method of Socket class to get an InputStream object, through which we can get the information sent to us by the target host:


InputStream inStream = sk.getInputStream();

Similarly, to send data to the target host, you can call the getOutputStream() method to get an output stream object.
The following example connects to a timing server and prints the returned information to standard output:


try 
{ 
Socket sk = new Socket("210.0.235.14",13); 
sk.setSoTimeout(3000); 
  InputStream inStream = sk.getInputStream();
  //Gets the input stream object
  Scanner sc = new Scanner(inStream); 
  //Print the data to the console
  while(sc.hasNextLine()) 
  { 
 String str = sc.nextLine(); 
 System.out.println("Output : " + str); 
  } 
  sk.close(); 
} 
catch(SocketTimeoutException e) //Timeout exception
{ 
  System.out.println("Time Out!"); 
} 
catch(Exception e) 
{ 
  e.printStackTrace(); 
}

The setSoTimeout() method in the code can set a timeout, which means that if a read or write operation is not completed, a SocketTimeoutException is thrown, and the connection can be closed by catching this exception.
Another timeout issue that must be addressed is the constructor of the Socket class


new Socket(host,port);

It blocks indefinitely until a successful connection to the target host is established. This is certainly not what we had hoped for. We can solve this problem by calling:


Socket sk = new Socker();
sk.connect(new InetSocketAddress(host,port),2000);
// Set the timeout time to 2 seconds 

Get the host address

The static method getByName(hostname) of the InetAddress class returns an InetAddress object that represents a host address, which encloses a four-byte sequence, the IP address of the host. Then call the getHostAddress() method to return a String object representing the IP address.

Some of the host names with high traffic will usually correspond to multiple IP addresses for load balancing. We can get all the host addresses by calling the getAllByName() method, which returns an array of InetAddress objects.

The following is a simple small program, the function is to print out the local IP address if you do not set parameters on the command line, if you specify the host name, then print out all the IP addresses of the host:


package cls; 
import java.net.*; 
public class ShowIP 
{ 
  public static void main(String[] args) 
  { 
    try 
    { 
      if(args.length > 0) 
      { 
        String hostName = args[0]; //The host name
        InetAddress[] addr = InetAddress.getAllByName(hostName);
        //Gets all the addresses for that host
        //Print out to the console
        for(InetAddress address : addr) 
        { 
          System.out.println(address.getHostAddress()); 
        } 
      } 
      else 
      { 
        System.out.println(InetAddress.getLocalHost().getHostAddress());
      } 
    } 
    catch(Exception e) 
    { 
      e.printStackTrace(); 
    } 
  } 
}

Three, the server side program

Server-side applications use the ServerSocket class to create sockets and bind them to local ports, such as


ServerSocket sock = new ServerSocker(8000);

The sock.accept() method, which keeps the program waiting for a connection, only returns a Socket object that represents a new connection when there is a client connection, which blocks the method.
Typically, a new thread is opened for each connection.
Here is a complete example of a server waiting for a connection at port 8400, each time a connection arrives, a new thread is opened to serve it, and the connection information is written to a log file:


package cls; 
import java.io.*; 
import java.net.*; 
import java.util.*; 
public class ServerDemo 
{ 
   
  public static void main(String[] args) 
  { 
    try 
    { 
      //ServerSocket servSocket = new ServerSocket(8000); 
      ServerSocket servSocket = new ServerSocket(8400); 
      int amount = 0; 
      while(true) 
      { 
        Socket client = servSocket.accept(); 
        ++amount; 
        Date time = new Date(); 
        String prompt = time.toString() + ":  The first " + amount + " A user  " + client.getInetAddress().getHostAddress() + "  The connected n"; 
        System.out.print(prompt); //Output information at the console
        ServerDemo.writeLog(prompt); //Write to a file
        //start a new Thread 
        Thread th = new Thread(new ServThread(client,amount)); 
        th.start(); 
      } 
    } 
    catch(Exception e) 
    { 
      e.printStackTrace(); 
    } 
  } 
  //Write to log file
  public static void writeLog(String str) 
  { 
    File logFile = new File("server-log.txt"); 
    try 
    { 
      FileWriter out = new FileWriter(logFile,true); 
      out.append(str); 
      out.close(); 
    } 
    catch(Exception e) 
    { 
      e.printStackTrace(); 
    } 
  } 
} 
 
class ServThread implements Runnable 
{ 
  private Socket client; 
  private int ix; 
  public ServThread(Socket soc,int ix) 
  { 
    client = soc; 
    this.ix = ix; 
  } 
  public void run() 
  { 
    try 
    { 
      InputStream inStream = client.getInputStream(); 
      OutputStream outStream = client.getOutputStream(); 
      Scanner recv = new Scanner(inStream); 
      PrintWriter send = new PrintWriter(outStream,true); 
      send.println(" Welcome ~ casual chat a few words! [ The input 'bye' Close connection ]"); 
      while(recv.hasNextLine()) 
      { 
        String str = recv.nextLine(); 
        if(str.equals("bye")) 
        { 
          send.println("See you later ~ ^-^"); 
          break; 
        } 
        send.println(" This is a test program, there is no function now "); 
      } 
      Date time = new Date(); 
      String prompt = time.toString() + ":  The first " + ix + " A user  " + client.getInetAddress().getHostAddress() + "  Disconnected connection n"; 
      System.out.print(prompt); 
      ServerDemo.writeLog(prompt); //Write to a file
      client.close(); 
    } 
    catch(Exception e) 
    { 
      e.printStackTrace(); 
    } 
  } 
}

This program has been put on the server, you can use the Telnet youthol.tk 8400 command to experience the results of this program

I hope this article has been helpful to your Java programming.


Related articles: