Java communication under the TCP protocol

Source: Internet
Author: User

Preliminary, but also to improve

Server

 PackageSix.four.five.server;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.OutputStreamWriter;Importjava.net.InetSocketAddress;ImportJava.net.ServerSocket;ImportJava.net.Socket;Importjava.net.SocketAddress;Importjava.util.ArrayList;Importjava.util.List;//: This is a server Public classSever { Public Static voidMain (string[] args) {//: Accepts the output stream from the client and reads the information in itlist<bufferedwriter> list =NewArraylist<bufferedwriter>(); Try {            //implement a server socket. The server socket waits for the request to pass through the network. It performs certain actions based on the request, and may then return the results to the requestor. ServerSocket Server =NewServerSocket (8888); System.out.println ("Server Started");  while(true) {                //This class implements a client socket (which can also be called a "socket"). Sockets are the endpoints of communication between two machines. Socket socket =server.accept (); System.out.println ("Client has been linked!"); //returns the input stream for this socket, which is the client's input stream, which is given to the thread and reads the data into the//InputStream is = Socket.getinputstream (); //convert a byte stream to a character streamInputStreamReader IR =NewInputStreamReader (Socket.getinputstream ()); //creating a buffered streamBufferedReader br =NewBufferedReader (IR); //returns the output stream of this socket, which is the output stream of the client, given to the collection list, to be sent to each clientOutputStream OS =Socket.getoutputstream (); //convert character streams to byte streamOutputStreamWriter ow =Newoutputstreamwriter (OS); //creating a buffered streamBufferedWriter BW =NewBufferedWriter (OW); //adding an output streamlist.add (BW); //upload the input stream and the collection to the thread, and execute the thread                NewMyThread (BR, List). Start (); }        } Catch(IOException e) {e.printstacktrace (); }    }}

Server's Thread

 PackageSix.four.five.server;//: Receive messages from clients on a continuousImportJava.io.BufferedInputStream;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.OutputStreamWriter;Importjava.util.List; Public classMyThreadextendsthread{//accept the collection of output streams    PrivateList<bufferedwriter>ow; //Buffered Streams    PrivateBufferedReader BR; //How threads are constructed     PublicMyThread (BufferedReader BR, list<bufferedwriter>ow) {         This. ow =ow; //this.is = new InputStreamReader (is);         This. BR =BR; } @Override Public  voidrun () {String msg=NULL;  while(true) {            Try {                 while(NULL! = (msg =Br.readline ())) {                    //Output StringSystem.out.println (msg); }                 for(BufferedWriter lo:ow) {//writes the information that is received to the client to the stream so that it is sent to each clientlo.write (msg);                Lo.flush (); }            } Catch(IOException e) {e.printstacktrace (); }        }    }}

Client

 Packagesix.four.five.clients;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.OutputStreamWriter;Importjava.net.InetAddress;ImportJava.net.Socket;Importjava.net.UnknownHostException;ImportJava.util.Scanner; Public classClients { Public Static voidMain (string[] args) {Try{Socket Socket=NewSocket (Inetaddress.getbyname ("192.168.0.124"), 8888); System.out.println ("You have Benn linked sever!"); //InputStream is =Socket.getinputstream (); InputStreamReader ir=NewInputStreamReader (IS); BufferedReader BR=NewBufferedReader (IR); //OutputStream OS =Socket.getoutputstream (); OutputStreamWriter ow=Newoutputstreamwriter (OS); BufferedWriter BW=NewBufferedWriter (OW); //Scanner input =NewScanner (system.in); System.out.println ("What your name?"); String name=Input.nextline (); System.out.print ("Now,you can Say Anything:"); String msg= ""; NewMyThread (BR). Start ();  while(! (Msg.equals ("Bye"))) {                //B = msg.getbytes ();msg = name + ":" +Input.nextline ();                Bw.write (msg);            Bw.flush (); }        } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }}

The client's thread

 Packagesix.four.five.clients;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader; Public classMyThreadextendsthread{PrivateBufferedReader BR;  PublicMyThread (BufferedReader br) { This. BR =BR; } @Override Public voidrun () {String msg=NULL;  while(true) {            Try {                 while(NULL! = (msg =Br.readline ()))                {System.out.println (msg); }            } Catch(IOException e) {e.printstacktrace (); }        }    }}

Java communication under the TCP protocol

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.