PrintWriter Write =New PrintWriter (Socket.getoutputstream ()); //Get the output stream of the socket Write.flush ();//Send data, refresh output streamInputStreamReader in =New New InputStreamReader (Socket.getinputstream ()); //Get input stream of socket server-side:
ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classService {serversocket server; Socket socket; PublicService () {//set up a server Try{Server=NewServerSocket (10086); System.out.println ("Start Service"); Onserver (); } Catch(IOException e) {System.out.print ("Failed to start service"); } } Private voidOnserver () {Try{Socket= Server.accept ();//Listening PortBufferedReader in=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); String Line; //continuously receives data from a linked socket Do{ Line=In.readline (); System.out.println ("Client Say:" +Line ); } while(!line.equals ("Quit")); In.close (); Socket.close (); Server.close (); } Catch(IOException e) {System.out.println ("Error" +e); } } Public Static voidMain (string[] args) {Service s=NewService (); }}
Client:
ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.Socket; Public classClient {Privatesocket socket; PublicClient () {//connecting to a server Try{Socket=NewSocket ("localhost", 10086); Handleinput (); } Catch(IOException e) {System.out.println ("Failed to connect Service"); } } Private voidHandleinput () {Try{bufferedreader br=NewBufferedReader (NewInputStreamReader (system.in)); PrintWriter Write=NewPrintWriter (Socket.getoutputstream ()); String ReadLine; Do{ReadLine=Br.readline (); Write.println (ReadLine); //writes to the output sideWrite.flush ();//Refresh, sendSystem.out.println (ReadLine); } while(!readline.equals ("quit!")); Write.close (); Socket.close (); } Catch(IOException e) {e.printstacktrace (); } } Public Static voidMain (string[] args) {Client C=NewClient (); }}
Java Socket Interface