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;Importjava.io.Serializable; 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;Importjava.io.IOException;Importjava.net.InetAddress;ImportJava.net.ServerSocket;ImportJava.net.Socket; 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;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.ObjectInputStream;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.Socket;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.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.ObjectOutputStream;ImportJava.io.OutputStream;ImportJava.net.Socket;Importjava.net.UnknownHostException;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 ("127.0.0.1", 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