Java Socket Communication

Source: Internet
Author: User

There are several steps to socket communication

Service side:

1. Creating the server, listening port

2. Service-side dead Loop accepts client requests

3. Get the client request and output

Client:

1. Create socket Connection Server

2. Sending data to the server

The service-side code is as follows:

 Public classServer { Public Static voidMain (string[] args)throwsIOException {createserver (); }    Private Static voidCreateserver ()throwsIOException {//1. Create a service-side socket, listening portServerSocket Server =NewServerSocket (8888); //2. The dead loop waits for the client to connectSocket client =NULL;  while(true){            //3. Get the socket that the client connects toClient =server.accept (); if(Client! =NULL) {System.out.println ("The client connection came up"); //4. Get client input and read it outBufferedReader Read =NewBufferedReader (NewInputStreamReader (Client.getinputstream ()));                System.out.println (Read.readline ());            Read.close (); }        }    }        }

The client code is as follows

 Public classClient { Public Static voidMain (string[] args)throwsIOException {createclient (); }    Private Static voidCreateClient ()throwsunknownhostexception, IOException {//Create clientSocket client =NewSocket ("127.0.0.1", 8888); //Client Connection service side//socketaddress endpoint = new Inetsocketaddress ("127.0.0.1", 8888);OutputStream OS =Client.getoutputstream (); OutputStreamWriter OSW=NewOutputStreamWriter (OS, "UTF-8")); BufferedWriter BW=NewBufferedWriter (OSW); Bw.write ("Hello");        Bw.flush ();        Os.close ();    Osw.close (); }}

Java Socket Communication

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.