Java Socket Programming Basics

Source: Internet
Author: User

1. [Code] read operation runable

1
PackageCom.hrd.test.socket;2 3 ImportJava.io.BufferedReader;4 Importjava.io.IOException;5 ImportJava.io.PrintWriter;6 7 /**8 * Author: ehomeud Founded in: 2015/4/15 13:159 */Ten Public classReadthreadImplementsRunnable { One A Privatebufferedreader BR; - PrivateString SC; - the Publicreadthread (BufferedReader br,string SC) { - This. br=BR; - This. sc =SC; - } + @Override - Public voidrun () { + while(true){ A Try { atString str =br.readline (); -System.out.println (sc + ":" +str); -}Catch(IOException e) { - e.printstacktrace (); - } - } in } -}
2. [Code] write operation runable
 PackageCom.hrd.test.socket;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.PrintWriter;/*** Author: ehomeud Founded in: 2015/4/15 13:20*/ Public classWritethreadImplementsRunnable {PrivatePrintWriter PW; PrivateBufferedReader BR;  PublicWritethread (printwriter pw, BufferedReader br) { This. PW =PW;  This. BR =BR; } @Override Public voidrun () {Try {             while(true) {pw.println (Br.readline ());            Pw.flush (); }        } Catch(IOException e) {e.printstacktrace (); }    }}
3. [Code] Server ServerSocket
 PackageCom.hrd.test.socket;ImportJava.io.*;ImportJava.net.ServerSocket;ImportJava.net.Socket;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** Author: ehomeud Founded in: 2015/4/15 10:00am*/ Public classServer { Public Static intPORT = 9999;  Public Static voidMain (string[] args) {serversocket s=NULL; Socket Socket=NULL; BufferedReader BR=NULL; PrintWriter PW=NULL; BufferedReader Console=NULL; Executorservice Pool= Executors.newfixedthreadpool (2); Try {            //setting up a server-side communication ports =NewServerSocket (PORT); System.out.println ("ServerSocket Start:" +s); //wait for the request, the method blocks until the request is receivedSocket =s.accept (); System.out.println ("Connection Accept Socket:" +socket); //used to receive requests from clientsBR =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); //used to send return information, send data to call the. Flush () methodPW =NewPrintWriter (NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())),true); Console=NewBufferedReader (NewInputStreamReader (system.in)); Pool.submit (NewReadthread (BR, "Server")); Pool.submit (NewWritethread (pw,console));  while(true) {Thread.Sleep (10000); }        } Catch(Exception e) {e.printstacktrace (); }finally{System.out.println ("Close in ..."); Try{console.close ();                Br.close ();                Pw.close ();                Socket.close ();            S.close (); } Catch(Exception E2) {} }}}
4. [Code] Client socket
 PackageCom.hrd.test.socket;ImportJava.io.*;ImportJava.net.Socket;ImportJava.util.concurrent.Executor;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** Author: ehomeud Founded in: 2015/4/15 10:10*/ Public classClient { Public Static voidMain (string[] args) {socket socket=NULL; BufferedReader BR=NULL; PrintWriter PW=NULL; Executorservice Pool= Executors.newfixedthreadpool (2); Try {            //Client socket Specifies the address and port number of the serverSocket =NewSocket ("127.0.0.1", Server.port); System.out.println ("Socket:" + socket+ "Client startup ..."); //same as Server principleBR =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); PW=NewPrintWriter (NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())); BufferedReader Console=NewBufferedReader (NewInputStreamReader (system.in)); //Submit ReadPool.submit (NewWritethread (pw,console)); Pool.submit (NewReadthread (BR, "Client"));  while(true) {Thread.Sleep (100000); }        } Catch(Exception e) {e.printstacktrace (); } finally {            Try{System.out.println ("Closed ...");                Br.close ();                Pw.close ();            Socket.close (); } Catch(IOException e) {e.printstacktrace (); }        }    }  }

Java Socket Programming Basics

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.