Java Network programming

Source: Internet
Author: User

. TCP Programming

The development of TCP programs using sockets (Sockets) in Java makes it easy to establish reliable, bidirectional, continuous, point-to-point communication connections.

In the socket program development, the server side uses Serversocke to wait for the client connection, for the Java Network program, each client uses a socket object representation.

. common methods of the ServerSocket class :

Serial number Method Type Describe
1 public serversocket (int port) throws IOException constructor function Creates a ServerSocket instance and listens on the specified port.
2 Public Socket Accept () throws IOException Common functions Waits for a client connection before this method connects until it blocks
3 Public inetaddress getinetaddress () Common functions Returns the IP address of the server
4 public boolean isClosed () Common functions Returns the closed state of the ServerSocket
5 public void Close () throws IOException Common functions Close ServerSocket

On each run of the server, the Accept () method waits for the client to connect, and after this method executes the server side will go into a blocking state until the program can continue down after the client is connected. The return value type of this method is the socket, each of which represents a client object.

. Common methods for socket classes:

Serial number Method Type Describe
1 Public Socket (String host, int port) throws Unknownhostexception,ioexception Structure Constructs a socket object, specifying the host name and connection port number to connect to the server.
2 Public InputStream getInputStream () throws IOException Ordinary Returns the input stream for this socket
3 Public OutputStream Getoutputstream () throws IOException Returns the output stream for this socket
4 public void Close () throws IOException Close this socket
5 public boolean isClosed () Determine if this socket is closed

. First TCP Program--echo program

The Echo program is a typical case of a network programming communication interaction called a response program, which is what the client enters, and the server adds "ECHO:" Before the content and sends the information back to the client.

The previous program code, the server side each execution completes, the server will exit, this is because the server side can accept only one client connection, mainly because the accept () method can only be used once, this program will pass

The loop method uses the Accept () method, so that after each client finishes executing, the server can wait for the user to connect again.

Single Thread Example:

1  Public classechoclient {2      Public Static voidMain (string[] args)throwsIOException {3 4Socket client =NewSocket ("localhost", 8888);5BufferedReader buf =NULL;6PrintStream out =NULL;7out =NewPrintStream (Client.getoutputstream ());8OUT.PRINTLN (1);9BufferedReader input =NULL;Teninput =NewBufferedReader (NewInputStreamReader (system.in)); OneBUF =NewBufferedReader (NewInputStreamReader (Client.getinputstream ())); A         BooleanFlag =true; -  -          while(flag) { theSystem.out.println ("Please Key in:"); -String str =input.readline (); - out.println (str); -             if("Bye". Equals (str)) { +Flag =false; -}Else { +String echo =buf.readline (); A  atSystem.out.println ("1111" +echo); -             } -         } - client.close (); - buf.close (); -     } in}

Single Thread Example:

1  Public classEchoserver {2      Public Static voidMain (string[] args)throwsIOException {3ServerSocket Server =NULL;4Socket client =NULL;5PrintStream out =NULL;6BufferedReader buf =NULL;7Server =NewServerSocket (8888);8         Booleanf =true;9          while(f) {TenSystem.out.println ("Server running,waiting for Client"); OneClient =server.accept (); Aout =NewPrintStream (Client.getoutputstream ()); -             //get information on client input -BUF =NewBufferedReader (NewInputStreamReader ( the Client.getinputstream ())); -             //instantiate the output side -out =NewPrintStream (Client.getoutputstream ()); -             BooleanFlag =true; +              while(flag) { -String str =buf.readline (); +                 if(str = =NULL|| "". Equals (str)) { AFlag =false; at}Else { -                     if("Bye". Equals (str)) { -Flag =false; -}Else { -Out.println ("ECHO" +str); -                     } in                 } -             } to out.close (); + client.close (); -         } the server.close (); *     } $ Panax Notoginseng}

multithreaded Example:

1  Public classEchothreadImplementsRunnable {2 3     PrivateSocket client =NULL;4 5      PublicEchothread (Socket client) {6          This. Client =client;7     }8 9      Public voidrun () {TenPrintStream out =NULL; OneBufferedReader buf =NULL; A  -         Try { -BUF =NewBufferedReader (NewInputStreamReader ( the Client.getinputstream ())); -out =NewPrintStream (Client.getoutputstream ()); -             BooleanFlag =true; -  +              while(flag) { -String str =buf.readline (); +                 if(str = =NULL|| "". Equals (str)) { AFlag =false; at}Else { -                     if("Bye". Equals (str)) { -Flag =false; -}Else { -Out.println ("ECHO:" +str); -                     } in                 } -             } to out.close (); + client.close (); -}Catch(Exception e) { the         } *     } $ Panax Notoginseng}

multithreaded Example:

1  Public classEchoserver {2      Public Static voidMain (string[] args)throwsIOException {3ServerSocket Server =NULL;4Socket client =NULL;5PrintStream out =NULL;6BufferedReader buf =NULL;7Server =NewServerSocket (8888);8         Booleanf =true;9          while(f) {TenSystem.out.println ("Server running,waiting for Client"); OneClient =server.accept (); A             NewThread (Newechothread (client)). Start (); -              -         } the server.close (); -     } -  -}

On the server side, each client socket connected to the server runs in a single thread, so that no matter how many client connections you have, you can complete the operation at the same time.

Not to be continued ...

Java Network programming

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.