TCP for Java socket programming

Source: Internet
Author: User

TCP-based socket communication:

Server-side:

    1. Create a server-side socket, that is, ServerSocket, specify the bound port, and listen for this port
    2. Call the Accept () method to start listening, waiting for the client to connect
    3. After the connection is established, read the request information sent by the customer through the input stream
    4. Send response information to the client via output flow
    5. Close related Resources

Client:

    1. Create a client socket, specify the server address and port
    2. After the connection is established, the message is sent to the server through the output stream
    3. Gets the input stream and reads the server-side response information
    4. Close Resource

Example: Server side:

ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;Importjava.net.InetAddress;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classServer { Public Static voidMain (string[] args) {Try {            //1. Create a server-side socket, which is serversocket, specify the bound port and listen for this portServerSocket serversocket=NewServerSocket (8888); Socket Socket=NULL; //log the number of clients            intCount=0; System.out.println ("* * * server is about to start, waiting for client connections * * *"); //loop monitoring waits for a client's connection             while(true){                //call the Accept () method to start listening, waiting for the client to connectsocket=serversocket.accept (); //Create a new threadServerthread serverthread=Newserverthread (socket); //Start ThreadServerthread.start (); Count++;//Count the number of clientsSystem.out.println ("Number of clients:" +count); InetAddress Address=socket.getinetaddress (); System.out.println ("IP for current client:" +address.gethostaddress ()); }        } Catch(IOException e) {e.printstacktrace (); }    }}

Client:

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 sideOutputStream Os=socket.getoutputstream ();//byte output streamPrintWriter pw=NewPrintWriter (OS);//wrapping the output stream as a print streamPw.write ("User name: Alice; Password: 789");            Pw.flush (); Socket.shutdownoutput ();//turn off the output stream//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 (); }    }}

Server Thread processing classes:

ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.Socket; Public classServerthreadextendsThread {//socket associated with this threadSocket socket =NULL;  PublicServerthread (socket socket) { This. Socket =socket; }    //A thread performs an action that responds to a client's request     Public voidrun () {InputStream is=NULL; InputStreamReader ISR=NULL; BufferedReader BR=NULL; OutputStream OS=NULL; PrintWriter PW=NULL; Try {            //gets the input stream and reads the client informationis =Socket.getinputstream (); ISR=NewInputStreamReader (IS); BR=NewBufferedReader (ISR); String Info=NULL;  while((Info=br.readline ())! =NULL){//iterating through the client's informationSystem.out.println ("I am the server, the client says:" +info); } socket.shutdowninput ();//close the input stream//gets the output stream that responds to the client's requestOS =Socket.getoutputstream (); PW=Newprintwriter (OS); Pw.write ("Welcome you!" "); Pw.flush ();//Call the Flush () method to buffer the output}Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }finally{            //Close Resource            Try {                if(pw!=NULL) Pw.close (); if(os!=NULL) Os.close (); if(br!=NULL) Br.close (); if(isr!=NULL) Isr.close (); if(is!=NULL) Is.close (); if(socket!=NULL) Socket.close (); } Catch(IOException e) {e.printstacktrace (); }        }    }}

To transfer objects using TCP traffic:

ObjectOutputStream oos=new objectoutputstream (OS);

User User=new User ("admin", "123");//Package As Object

Oos.writeobject (user);//serialization

Tips:

Priority issue: Serverthread.setpriority ();//lower priority to prevent slow running

Input and output stream problem: the same socket, close the output stream will close the associated socket, so do not close the output stream, and finally close the socket.

TCP for Java socket programming

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.