Java socket-tcp

Source: Internet
Author: User
Tags try catch

The "server Side" creates the ServerSocket object, the binding listening port through the Accept () method listens to the client request establishes the connection, through the input stream reads the request information sent by the client through the output flow to the client sends the response information closes the related resource "The client" creates the socket object, Indicates the server address and port number that need to be connected after the connection is established, send request information through the output flow to the server to get the server response information through the input stream shutdown related resources "multi-threaded Server" Apply multithreading to implement communication between server and multi-client basic Step 1. Server-side Create ServerSocket, loop call Accept () Wait for Client Connection 2. Client creates a socket and requests a connection to the server 3. The server side accepts the client request and creates a Socke connection with the customer 4. Connect the two sockets on a separate thread on the dialog 5. Server side continues to wait for new Connection "code":
 PackageTestsocket;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.Socket;/*** Server Thread Processing class * *@authorBuddha **/ Public classServerthreadextendsThread {//socket associated with this threadSocket socket =NULL; //method of constructing with parameters     PublicServerthread (socket socket) { This. Socket =socket; }    //A thread performs an action that responds to a client's request     Public voidrun () {//byte input streamInputStream is =NULL; //to improve read performance, wrap the byte input stream and turn it into a character streamInputStreamReader ISR =NULL; //adds a buffer to a character stream and reads it in a buffered mannerBufferedReader br =NULL; OutputStream OS=NULL; //Convert to print streamPrintWriter PW =NULL; //Select the code that will throw the exception, press Shift+alt+z and then you can select the try catch and the exception will be thrown automatically        Try {            //3. Get an input stream to read client informationis =Socket.getinputstream (); ISR=NewInputStreamReader (IS); BR=NewBufferedReader (ISR); //get client-submitted informationString info =NULL; //looping through client-submitted information//read one line at a time             while(info = br.readline ())! =NULL) {System.out.println ("I am the server," said the client, "+info); }            //close the input streamSocket.shutdowninput (); //4. Get the output stream in response to client requestsOS =Socket.getoutputstream (); PW=Newprintwriter (OS); Pw.write (Welcome); Pw.flush ();//Refresh Cache}Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally {            //5. Close Resources            Try {                //if (pw = null)//for the same socket, if the output stream is turned off, the socket will also be closed, so it is generally not necessary to close the output stream and close the socket directly. //pw.close ();                if(OS! =NULL) Os.close (); if(OS! =NULL) Br.close (); if(ISR! =NULL) Isr.close (); if(Is! =NULL) Is.close (); if(Socket! =NULL) Socket.close (); } Catch(IOException e) {e.printstacktrace (); }        }    }}
Serverthread.java
 PackageTestsocket;Importjava.io.IOException;Importjava.net.InetAddress;ImportJava.net.ServerSocket;ImportJava.net.Socket;/*** TCP protocol-based communication for user login *@authorBuddha * Server Side*/ Public classServer { Public Static voidMain (string[] args) {Try {            //1. Create a server-side socket that is both serversocket, specifying the bound port, and listening on this portServerSocket ServerSocket =NewServerSocket (8888); Socket Socket=NULL; //log the number of clients            intCount = 0; //2. Call the Accept () method to start listening, waiting for the client's linkSYSTEM.OUT.PRINTLN ("======= server is about to start, wait for client link ======"); //Loop monitoring waiting for a client link             while(true) {Socket=serversocket.accept (); //Create a new threadServerthread serverthread=Newserverthread (socket); //set thread priority, 1-10. Defaults to 5 to avoid slow run timesServerthread.setpriority (4); //Start ThreadServerthread.start (); //Count the number of clientscount++; System.out.println ("Number of clients:" +count); //Get inetaddress InstanceInetAddress address=socket.getinetaddress (); //get the IP of the clientSYSTEM.OUT.PRINTLN ("IP for current client:" +address.gethostaddress ()); }        } Catch(IOException e) {e.printstacktrace (); }            }}
Server.java
 PackageTestsocket;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.Socket;Importjava.net.UnknownHostException; Public classClient { Public Static voidMain (string[] args) {Try {            //1. Create a client socket, specify the server address and PortSocket socket =NewSocket ("localhost", 8888); //2. Get the output stream and send the message to the server//byte output streamOutputStream OS =Socket.getoutputstream (); //wrapping the output stream as a print streamPrintWriter PW =Newprintwriter (OS); Pw.write ("User name: admin; Password: 123"); //refreshes the cache and outputs information to the serverPw.flush (); //turn off the output stream//You cannot use Pw.close () to close the output stream, you need to use Socket.shutdownoutput () to close the current output stream and end the output of the dataSocket.shutdownoutput (); //3. Get the input stream and read the server-side response informationInputStream is=Socket.getinputstream (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (IS)); String Info=NULL;  while((Info=br.readline ())! =NULL) {System.out.println ("I am the client, the server says" +info); }                        //4. Close ResourcesBr.close ();            Is.close ();            Pw.close ();            Os.close ();        Socket.close (); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }        //    }}
Client.java

Java socket-tcp

Related Article

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.