Client.java
Import java.io.*; import java.net.*; import java.util.*; Public classClient { Public Static voidMain (String args[]) {Scanner Scanner=NewScanner (System.inch); Socket Mysocket=NULL; DataInputStreaminch=NULL; DataOutputStream out=NULL; Thread ReadData; Read Read=NULL; Try{mysocket=NewSocket (); Read=NewRead (); ReadData=NewThread (read); System. out. Print ("Enter the IP of the server:"); String IP=Scanner.nextline (); System. out. Print ("Input port number:"); intPort =Scanner.nextint (); if(mysocket.isconnected ()) {}Else{inetaddress Address=Inetaddress.getbyname (IP); Inetsocketaddress socketaddress=Newinetsocketaddress (Address,port); Mysocket.connect (socketaddress); inch=NewDataInputStream (Mysocket.getinputstream ()); out=NewDataOutputStream (Mysocket.getoutputstream ()); Read.setdatainputstream (inch); Readdata.start (); } } Catch(Exception e) {System. out. println ("Server is disconnected"+e); } System. out. Print ("Enter the radius of the garden (discard Please enter N):"); while(Scanner.hasnext ()) {Doubleradius=0; Try{radius=scanner.nextdouble (); } Catch(inputmismatchexception exp) {system.exit (0); } Try { out. writedouble (RADIUS); } Catch(Exception e) {} }}}
Read.java
Import java.io.*; Public classRead implements Runnable {DataInputStreaminch; Public voidSetdatainputstream (DataInputStreaminch) { This.inch=inch; } Public voidrun () {Doubleresult=0; while(true) { Try{result=inch. readdouble (); System. out. println ("area of the circle:"+result); System. out. Print ("Enter the radius of the garden (discard Please enter N):"); } Catch(IOException e) {System. out. println ("is disconnected from the server"+e); Break; } } }}
Server.java
Import java.io.*; import java.net.*; import java.util.*; Public classServer { Public Static voidMain (String args[]) {ServerSocket server=NULL; Serverthread thread; Socket for you=NULL; while(true) { Try{server=NewServerSocket ( .); } Catch(IOException E1) {System. out. println ("is listening .");//ServerSocket objects cannot be created repeatedly } Try{System. out. println ("waiting for customer to call"); You=server.accept (); System. out. println ("customer's address:"+you.getinetaddress ()); } Catch(IOException e) {System. out. println ("Waiting for customer"); } if(you!=NULL) { NewServerthread (You). Start ();//start a dedicated thread for each customer } } }}classServerthread extends Thread {socket socket; DataOutputStream out=NULL; DataInputStreaminch=NULL; String s=NULL; Serverthread (Socket t) {socket=T; Try{ out=NewDataOutputStream (Socket.getoutputstream ()); inch=NewDataInputStream (Socket.getinputstream ()); } Catch(IOException e) {}} Public voidrun () { while(true) { Try{DoubleR=inch. readdouble ();//blocked state, unless a message is read Doublearea=math.pi*r*R; out. writedouble (area); } Catch(IOException e) {System. out. println ("Customer Leave"); return; } } } }
Java Socket Network Programming (multithreading Technology)