/*** TCP: Transmission Control Protocol, the use of three-way handshake to ensure accurate connection operation. * UDP: Datagram protocol, send datagram, for example: SMS or QQ message. *//*** TCP server-side programs*/ Public classMain { Public Static voidMain (string[] args) {Try{serversocket S1=NewServerSocket (57712);//Create a server-side socketSYSTEM.OUT.PRINTLN ("Server is started, waiting for connection ....")); Socket s= S1.accept ();//waits for the client to connect, blockingString info = "Hello World---\ n"; //constructs a single byte output streamBufferedWriter BW =NewBufferedWriter (NewOutputStreamWriter (S.getoutputstream ())); Bw.write (info); Bw.close (); } Catch(IOException ex) {ex.printstacktrace (); } }}
/*** TCP client program*/ Public classClientdemo { Public Static voidMain (string[] args) {Try{System.out.println ("Good"); //Create a Client socket object (ip/host name, port number)Socket S1 =NewSocket ("172.31.150.27", 57712); System.out.println ("Connection to server succeeded"); //constructs a character input streamBufferedReader br =NewBufferedReader (NewInputStreamReader (S1.getinputstream ())); String Info=Br.readline (); SYSTEM.OUT.PRINTLN (info); Br.close (); } Catch(IOException ex) {ex.printstacktrace (); } }}
/*** Echo Server-side program*/ Public classMain { Public Static voidMain (string[] args)throwsIOException {serversocket s=NewServerSocket (12347); System.out.println ("Server has started. Is waiting .... "); BooleanFlag =true; while(flag) {System.out.println ("Is waiting for connection ...."); Socket S0=s.accept (); System.out.println ("Client IP:" +s0.getinetaddress (). Gethostaddress () + "Connected! "); //get input and output streamBufferedReader br =NewBufferedReader (NewInputStreamReader (S0.getinputstream ())); PrintStream PS=NewPrintStream (NewBufferedoutputstream (S0.getoutputstream ())); BooleanBOOL =true;//Loop receive Data while(BOOL) {String Info=Br.readline (); if(info==NULL|| "Bye". Equals (info)) {bool=false; }Else{System.out.println (info); Ps.println ("Echo:" +info); Ps.flush (); }} ps.close (); Br.close (); } }}
/*** Echo client program*/ Public classClientdemo { Public Static voidMain (string[] args)throwsioexception{//Create a Client socket object (ip/host name, port number)Socket S0 =NewSocket ("172.31.150.27", 12347); System.out.println ("Connection to server succeeded"); Scanner input=NewScanner (system.in); BooleanFlag =true; PrintStream PS=NewPrintStream (NewBufferedoutputstream (S0.getoutputstream ())); BufferedReader BR=NewBufferedReader (NewInputStreamReader (S0.getinputstream ())); while(flag) {System.out.println ("Please enter:"); String Info=Input.next (); if("Bye". Equals (info)) {Flag=false; }Else{ps.println (info); Ps.flush (); System.out.println (Br.readline ()); }} br.close (); Ps.close (); }}
Java Notes 15__TCP Server, client program/ECHO Program/