The Transport entity class object for Java sockets

Source: Internet
Author: User

One, TCP programming

The TCP protocol is connection-oriented, reliable, and orderly, sending data in a byte-stream manner. The Java implementation of TCP communication relies on 2 classes: The client's socket class and the server-side ServerSocket class.

The socket model based on TCP communication is as follows:

The implementation steps for socket communication are as follows:

1. Create server-side socket:serversocket and client socket:socket;

2. Open the Inputstream/outputstream connected to the socket;

3. Read and write the socket in accordance with the Protocol;

4. Close the InputStream and OutputStream and sockets.

Here is an example: the implementation function is that the client sends a user-class entity object to the server, and the server opens a processing thread to print the user information and sends a "welcome login" to the client each request is received.

1) Engineering structure

2) Server and client information Exchange class: User

In order to be able to achieve transmission. The client and server have the same package structure as the user class, and the class must be serialized

User class

 PackageCom.model;; Public classUserImplementsSerializable {Private intID; PrivateString name; PrivateString password;  PublicUser (intID, string name, string password) {    Super();  This. ID =ID;  This. Name =name;  This. Password =password; } @Override PublicString toString () {return"User [id=" + ID + ", name=" + name + ", password=" + password+ "]"; } }

3) Service side

Simpleserver class, primarily for accepting requests and opening processing threads

 PackageSimplesocketserver;;;;; Public classSimpleserver { Public Static voidMain (string[] args) {Try{serversocket ServerSocket=NewServerSocket (9999); intCount = 0;//log the number of clientsSYSTEM.OUT.PRINTLN ("Server started, waiting for client connection ... "); Socket Socket=NULL;  while(true) {Socket=serversocket.accept (); ++count; Thread Serverhandlethread=NewThread (NewServerhandlethread (socket)); Serverhandlethread.setpriority (4);                Serverhandlethread.start (); System.out.println ("On-line clients have" + Count + "! "); InetAddress inetaddress=socket.getinetaddress (); System.out.println ("The IP address of the current client is:" +inetaddress.gethostaddress ()); }        } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}

Serverhandlethread, the thread that the server handles to the socket

 PackageSimplesocketserver;;;;;;;ImportCom.model.User; Public classServerhandlethreadImplementsrunnable{Socket Socket=NULL;  PublicServerhandlethread (socket socket) {Super();  This. Socket =socket; } @Override Public voidrun () {//TODO auto-generated Method StubOutputStream OS =NULL; PrintWriter PW=NULL; Try{InputStream is=Socket.getinputstream (); ObjectInputStream Ois=NewObjectInputStream (IS); //The ReadObject () method must ensure that the user package name is consistent between the server and the client, or there will be no class errors foundSYSTEM.OUT.PRINTLN ("Object sent by client:" +(User) ois.readobject ()); Socket.shutdowninput ();//Disabling the input stream for socketsos=Socket.getoutputstream (); PW=Newprintwriter (OS); Pw.println ("Welcome to login!" ");            Pw.flush ();                    Socket.shutdownoutput (); } Catch(IOException |classnotfoundexception e) {            //TODO auto-generated Catch blockE.printstacktrace (); }finally{            Try{                if(pw!=NULL) {pw.close (); }                if(os!=NULL) {os.close (); }                if(socket!=NULL) {socket.close (); }            }Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }    } 

4) Client

 Packagesimplesocketclient;;;;;;;;;Importjava.nio.file.attribute.UserPrincipalNotFoundException;ImportJavax.sound.midi.MidiDevice.Info;ImportCom.model.User;/*** Socket communication based on TCP protocol, implement user login-client*/ Public classClient { Public Static voidMain (string[] args) {//1. Create the client socket, specify the IP and port of the server        Try{Socket Socket=NewSocket ("", 9999); //2. Gets the output stream of the socket that is used to send information to the serverOutputStream OS =Socket.getoutputstream (); ObjectOutputStream Oos=Newobjectoutputstream (OS); Oos.writeobject (NewUser (1, "root", "123456"));            Socket.shutdownoutput (); String infostring=NULL; //3. Get the input stream and get the server informationInputStream is =Socket.getinputstream (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (IS)); String Info=NULL;  while((Info=br.readline ())! =NULL) {System.out.println ("Server-side information:" +info);            } socket.shutdowninput ();            Oos.close ();            Os.close ();            Is.close ();            Br.close ();        Socket.close (); } Catch(unknownhostexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}

The Transport entity class object for Java sockets

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: 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.