1. Using the blocking readUTF (); Long-Connection
The 3 main aspects of a 2.java socket are as follows
1) accept block until a connection is accepted and a client object instance is returned
2) getInputStream ()
3) Getoutputstream ()
Client code:
Public classClientsocket { Public Static FinalString ip= "10.100.63.18"; Public Static Final intport=667; Public Static voidMain (string[] args) {System.out.println ("Client-initiated ..."); while(true) {Socket Socket=NULL; Try{Socket=NewSocket (Ip,port); //socket.setsotimeout (+);DataOutputStream out=NewDataOutputStream (Socket.getoutputstream ()); String Send= "Hello"; Out.writeutf (send);//client sends to server//Thread.Sleep (+);DataInputStream in=NewDataInputStream (Socket.getinputstream ()); System.out.println ("The client Received:" +In.readutf ());// Out.close (); In.close (); }Catch(Exception e) {System.out.println ("Client Exception"); }finally{ if(socket!=NULL){ Try{socket.close (); }Catch(IOException e) {}}} } }}
Service-Side code:
Public classServer { Public Static intport=667; Public Static voidMain (string[] args) {System.out.println ("Server startup ..."); Server server=NewServer (); Server.init (); } Private voidinit () {//TODO auto-generated Method StubServerSocket sock =NULL; Try{sock=NewServerSocket (PORT); while(true) {Socket Client=sock.accept (); NewHandlerthread (Client); } }Catch(Exception e) {}finally{ if(sock!=NULL){ Try{sock.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } } } Private classHandlerthreadImplementsrunnable{PrivateSocket SC; PublicHandlerthread (Socket client) {SC=client;//try {//sc.setsotimeout (+);//} catch (SocketException e) {// //TODO auto-generated Catch block//e.printstacktrace ();// } NewThread ( This). Start (); } @Override Public voidrun () {//TODO auto-generated Method Stub Try{DataInputStream input=NewDataInputStream (Sc.getinputstream ()); System.out.println ("Processing client data:" +Input.readutf ()); DataOutputStream Output=NewDataOutputStream (Sc.getoutputstream ()); String s= "Hello,i has received your message"; Output.writeutf (s); Output.close (); Input.close (); }Catch(eofexception e) {System.out.println ("Server Eofexception Exception"); }Catch(IOException e) {System.out.println ("Server Eofexception Exception"); }finally{ if(sc!=NULL){ Try{sc.close (); }Catch(Exception e) {SC=NULL; } } } }} }
Run Result: (Run server first, run client)
Handling client data: Hello processing client data: Hello Client Received: Hello,i has received your message client received: Hello,i has received your message
Java socket client and server-side communication