Java Network Programming (i)

Source: Internet
Author: User
Tags stub

Reference: Java Core Technology Volume II

1. Connect to the server using the Telent tool

Open Telnet: Right-click on the computer, select Properties, Control Panel, home, programs, turn Windows features on or off, and select Telnet Client in the pop-up window.

CMD to open a command-line window,

Method One: Enter:

Telnet time-a.timefreq.bldrdoc.gov 13

Method Two:

First, in the command window, type: Telnet, and then enter in the Telnet window that pops up:

 Time  -

The result is:

Description is already connected to the "time of day" service that is supported by most UNIX computers. By convention, the "Time of day" service is always connected to port 13.

The following Java implementation is consistent with the use of the Telnet tool, which is to connect to a port and print the information it finds.

 Public classSockettest { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        Try{Socket s=NewSocket ("time-a.timefreq.bldrdoc.gov", 13);//Open a socketS.setsotimeout (1000);//Socket Timeout Settings            Try{InputStream instream= S.getinputstream ();//returns the input stream for this socketScanner in =NewScanner (instream);//get data from a stream                                 while(In.hasnextline ()) {//data in the output streamString line =In.nextline ();                System.out.println (line); }            }            Catch(Interruptedioexception exception) {//Get Timeout ExceptionException.printstacktrace (); }            finally{s.close ();//close this socket            }        }        Catch(IOException e) {e.printstacktrace (); }    }}

2. Get the IP address

The following Java code gets the IP address of the host. If a host name is specified, the IP address of the given host is printed out, and if no host is specified, the IP address of the local host is printed.

The given host name can be set in the Run->run Configurations->arguments->program Arguments. When set, click Apply->run.

 Public classInetaddresstest { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        Try{            if(Args.length > 0) {//gets the host name from the external inputString host = Args[0]; /*** Static inetaddress Getbyname (String Host) Method: Returns the IP address of the given host * static InetAddress Geta Llbyname (String Host) Method: Returns an array of all IP addresses for a given host*/inetaddress[] Addresses=Inetaddress.getallbyname (host);  for(inetaddress a:addresses) System.out.println (a); }            Else{                //static inetaddress Getlocalhost () returns the local hostInetAddress localhostaddress =Inetaddress.getlocalhost ();                System.out.println (localhostaddress); //byte[] GetAddress () returns the original IP address of this InetAddress object (in byte array form)                byte[] Addressbyte =localhostaddress.getaddress ();                System.out.println (Addressbyte); //string gethostaddress () returns the IP address in the form of a stringString Addressinte =localhostaddress.gethostaddress ();                System.out.println (Addressinte); //String GetHostName () returns the host nameString Localhostname =Localhostaddress.gethostname ();            System.out.println (Localhostname); }        }        Catch(Exception e) {e.printstacktrace (); }    }

3. Implementing the Server

Implement a simple server that can send messages to the client. Once the server program is started, it waits for a client to connect to its port. The port selected here is 8189. Java implementations:

 Public classEchoserver { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        Try{serversocket s=NewServerSocket (8189);///Set up a server responsible for monitoring 8189 portsSocket Incoming= S.accept ();//Once the client sends the correct connection request to the port, the method returns a socket object representing the connection, which can be used to get the input and output streams            Try{InputStream instream= Incoming.getinputstream ();//the input stream used to get the serverOutputStream OutStream = Incoming.getoutputstream ();//the output stream used to get the serverScanner in=NewScanner (instream);//Replace the server's input flow with a scannerPrintWriter out =NewPrintWriter (OutStream,true /*AutoFlush*/);//Replace the server's output stream with a writerOut.println ("Hello, Enter BYE to exit.");//send a greeting message to the client                BooleanDone =false;  while(!done &&In.hasnextline ()) {String Line= In.nextline ();//get the input stream of the clientOut.println ("Echo:" + line);//the client's output stream                    if(Line.trim (). Equals ("BYE"))//When the client input is bye, exitDone =true; }            }            finally{incoming.close ();//close the socket in which the connection comes in            }        }        Catch(IOException e) {e.printstacktrace (); }    }}

Run: Click to run, and then enter in the Command line window:

// or telnet 127.0.0.1 8189

4. Service for multiple clients

Use threads to troubleshoot multiple clients connecting to the server at the same time. Whenever the program establishes a new socket connection, that is, when the accept () method is successfully invoked, a new thread is created to handle the connection between the server and the client, and the main program returns immediately and waits for the next connection. Java implementations:

 Public classThreadedechoserver { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        Try{            inti = 1; ServerSocket s=NewServerSocket (8189);  while(true){//Multiple ClientsSocket incoming =s.accept (); System.out.println ("Spawning" + i);//The output on the server side. Runnable r =NewThreadedechohandler (incoming); Thread T =NewThread (R);//Create a threadT.start (); i++; }        }        Catch(IOException e) {e.printstacktrace (); }    }}/** The Run method that implements the Runnable interface. */classThreadedechohandlerImplementsrunnable{PrivateSocket incoming;  PublicThreadedechohandler (Socket i) {incoming=i; }     Public voidrun () {//TODO auto-generated Method Stub        Try{            Try{InputStream instream=Incoming.getinputstream (); OutputStream OutStream=Incoming.getoutputstream (); Scanner in=NewScanner (instream); PrintWriter out=NewPrintWriter (OutStream,true /*AutoFlush*/); Out.println ("Hello! Enter BYE to Exit "); BooleanDone =false;  while(!done &&In.hasnextline ()) {String Line=In.nextline (); Out.println ("Echo:" +Line ); if(Line.trim (). Equals ("BYE")) done=true; }            }            finally{incoming.close (); }        }        Catch(IOException e) {e.printstacktrace (); }    }}

Run Result: You can open multiple Telnet windows and switch the input information between these windows.

Java Network Programming (i)

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.