Java Web Learning Note 1: Writing a simple client/server program with a (server) socket

Source: Internet
Author: User

    1. First, it is clear that the socket class provides the getInputStream () method and the Getoutputstream () method, respectively, to return the input stream InputStream object and the output stream OutputStream object. The program simply writes data to the data stream, sends the data to the other person, and receives data from the other party simply by reading the data from the input stream.

    2. Create a server program DemoServer01  

public class demoserver01 {/** *  @author   Shepherd's Queen   11/12 * @ param args *  creating mutual communication between the server and the client  */private int port = 9999;private  Serversocket server;public static void main (String[] args)  {new  DemoServer01 (). Servertalk ();} Public demoserver01 () {try {server =new  serversocket (9999); SYSTEM.OUT.PRINTLN ("Server starts and listens on port: "  + server.getlocalport ()  );}  catch  (ioexception e)  {e.printstacktrace ();}} Output stream   public printwriter getwriter (socket socket)  throws ioexception{ Outputstream outsocket = socket.getoutputstream ();//Parameter True indicates that each line is written, the PrintWriter cache automatically overflows, Write the data to the destination. Return new printwriter ( outSocket, true );}   Input stream Public bufferedreader getreader (socket socket)  throws ioexception{ Inputstream insocket = sOcket.getinputstream ();//  parameters  Reader                      //Parameters  InputStream     return new bufferedreader ( new inputstreamreader ( inSocket )  );} Public void servertalk () {socket socket = null;try {socket =  Server.accept ();   //has been listening for the client's connection printwriter pw = getwriter (socket); Bufferedreader br = getreader (socket); Bufferedreader localreader = new bufferedreader ( new inputstreamreader (  system.in )  ); String msg = null;while (True) {while (  (Msg = br.readline ()  )  !=  null ) {System.out.println ("Client to server you say: "  + msg), if ( msg.equals ("Bye")) { SYSTEM.OUT.PRINTLN ("The client is actively disconnecting from you."); break;} System.out.print ("Server-to-client:  "  ); String insTring = localreader.readline ();p w.println ( inString ); if (  instring.equals ("Bye" ) {System.out.println ("Server Disconnected from client  "  + socket.getinetaddress ()  + " ");  catch  (exception e)  {e.printstacktrace ();} Finally{if ( socket != null ) {try {socket.close ();}  catch  (ioexception e)  {e.printstacktrace ();}}}}

For a server program, the most important method is the Servertalk () method, which waits for a client's connection request, and the Server.accept () method returns a socket object, which means that a connection is established with a customer. The output stream and input stream are then obtained from the socket object, and the decibel is decorated with printwriter and BufferedReader. The BufferedReader ReadLine () method is then constantly called to read the client-sent string, returning a string to the client in the call to PrintWriter's println () method. If it is "Bye", end the communication and call the Socket.close () method to disconnect.


3. Create a client program DemoClient01

public class democlient01 {private string host =  "localhost";p rivate  Int port = 9999;private socket socket;public static void main (String[]  args)  {new democlient01 (). Clienttalk ();} Public democlient01 () {try{socket = new socket (host,port);   // Create the Socket object System.out.println ("Client connected to server ..."); catch  (unknownhostexception e)  {e.printstacktrace ();}  catch  (ioexception e)  {e.printstacktrace ();}} Public printwriter getwriter (Socket socket)  throws IOException{OutputStream  Outsocket = socket.getoutputstream (); Return new printwriter ( outSocket,true);} Public bufferedreader getreader (Socket socket)  throws IOException{InputStream  Insocket = socket.getinputstream (); Return new bufferedreader ( new  InputStreamReader (Insocket)  );} PublIc void clienttalk () {try {bufferedreader br = getreader (socket); Printwriter pw = getwriter (socket); Bufferedreader localreader = new bufferedreader ( new inputstreamreader (System.in )  ); string msg = null; System.out.print ("Client says:  to the server"); while (  (Msg = localreader.readline ()  )  !=  null ) {pw.println (msg), if ( msg.equals (  "Bye"  )) {SYSTEM.OUT.PRINTLN ("client actively disconnects from the server."); break;} String readstring = br.readline (); SYSTEM.OUT.PRINTLN ("Server-to-client you say: "  + readString  ); if ( readstring.equals ( ) Bye " ) {System.out.println (" The server has actively disconnected your connection with the client. "); break;} System.out.print ("Client says:  to the server");}}  catch  (unknownhostexception e)  {e.printstacktrace ();}  catch  (ioexception e)  {e.printstacktrace ();} Finally{try {socket.close ();}  catch  (ioexception e)  {e.printstacKtrace ();}}} 

For the client program, the most important is the Clienttalk () method, which continuously reads the string that the user has entered from the console, sends it to the server program, and prints the string returned by the server to the console.




Java Web Learning Note 1: Writing a simple client/server program with a (server) socket

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.