Java Network programming Simple server-side client application instance _java

Source: Internet
Author: User
Tags set time thread class

This article describes the simple server-side client application of Java network programming. Share to everyone for your reference. Specifically as follows:

In Java, we use Java.net.Socket and its related classes to complete the related functions of the network. The socket class is easy to use because Java technology hides the complex process of building a network connection and sending data over a connection. The following are only applicable to the TCP protocol.

One, connect to the server

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

Socket SK = new socket ("210.0.235.14", 13);

Where 210.0.235.14 is a dotted decimal string object that represents the IP address (or host name) of the destination host, and 13 specifies that 13 ports are connected to the target host. The 210.0.235.14 here is a service server in Hong Kong, the default port for the timing server is generally 13.
Note that the program blocks before successfully connecting to the server.
You can then use the getInputStream () method of the socket class to get a InputStream object that 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 function is to connect the timing server and print the returned information to the standard output:

Try 
{ 
Socket SK = new Socket ("210.0.235.14"); 
Sk.setsotimeout (3000); 
  InputStream instream = Sk.getinputstream ();
  Get the input stream object 
  Scanner sc = new Scanner (instream); 
  Prints 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 the timeout time, that is, if the read-write operation has not been completed if the set time is exceeded, the sockettimeoutexception is thrown, and the connection can be closed by capturing the exception.
There is also a timeout problem that must be resolved, is the constructor of this socket class

New Socket (Host,port);

is blocked indefinitely until a connection to the target host is successfully established. This is certainly not what we want. We can solve this problem by calling the following methods:

Socket SK = new Socker ();
Sk.connect (New Inetsocketaddress (Host,port),);
Set timeout time to 2 seconds

Second, obtain the host address

The static method Getbyname (hostname) of the InetAddress class can return a InetAddress object that represents a host address that encloses a 4-byte sequence, the IP address of the host. Then call the Gethostaddress () method to return a string object that represents the IP address.

Some host names with a large number of accesses typically correspond to multiple IP addresses to achieve load balancing. We can call the Getallbyname () method to get all the host addresses, which returns an array of InetAddress objects.

Here is a simple applet, the realization of the function is that if you do not set the parameters in the command line, print out the local IP address, if the host name is specified, then print out the host all IP address:

Package CLS; 
Import java.net.*; 
public class Showip 
{public 
  static void Main (string[] args) 
  { 
    try 
    { 
      if (args.length > 0) 
      { 
        String hostName = args[0];//host name 
        inetaddress[] addr = Inetaddress.getallbyname (hostName);
        Get all Address 
        //printout of this host to console for 
        (inetaddress address:addr) 
        { 
          System.out.println ( Address.gethostaddress ()); 
        } 
      else 
      { 
        System.out.println (Inetaddress.getlocalhost (). gethostaddress ());
      } 
    catch (Exception e) 
    { 
      e.printstacktrace (); 
    } 
  } 
}

Third, server-side programs

The server-side application uses the ServerSocket class to create the socket and'll it to the local port, as

ServerSocket sock = new Serversocker (8000);

The

Sock.accept () method keeps the program waiting for the connection, which returns a Socket object that represents the new connection only if there is a client connection, that is, the method blocks.
This is typically a new thread for each connection to serve.
The following is a complete example where the server waits for a connection at Port 8400 and, whenever the connection arrives, opens a new thread for its service and writes the connection information to the log file:

Package CLS; 
Import java.io.*; 
Import java.net.*; 
Import java.util.*; 
      public class Serverdemo {/** * @param args */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 () + ": First" + Amount + "user" + client.getinetaddress (). Gethostaddress () + "connected \ n"; System.out.print (prompt); Output information in the console Serverdemo.writelog (prompt); 
        Write to file//start a new thread thread th = new Thread (new Servthread (Client,amount)); 
      Th.start (); 
    } catch (Exception e) {e.printstacktrace (); 
    }//write 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 (); 
  }}/* * Service Thread class */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 ~ casually Chat a few words!") 
      [Enter ' bye ' close join] "); 
        while (Recv.hasnextline ()) {String str = recv.nextline (); 
          if (Str.equals ("Bye")) {send.println ("you later ~ ^-^"); 
        Break 
      Send.println ("This is a test program, now there is no function oh"); 
      Date time = new Date (); String prompt = Time.tostrING () + ": First" + IX + "user" + client.getinetaddress (). Gethostaddress () + disconnected \ \ n; 
      System.out.print (prompt); Serverdemo.writelog (prompt); 
    Write to 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 will help you with your Java programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.