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