Haven't written a blog for a long time, the previous period busy doing projects, delayed some time, today began to continue to write ~
Today, the simple application of socket communication, about what is the socket and some of the basics of network programming, is not mentioned here, only the most simple to understand the practical things.
1, first look at the TCP protocol based on the socket server and client communication model:
Socket Communication steps: (simple 4 steps)
1. Set up server ServerSocket and client sockets
2. Open the output input stream connected to the socket
3. Read and write operations in accordance with the Protocol
4. Close the corresponding resource
2. Associated APIs:
1. First look at the ServerSocket
Class ServerSocket
This class implements 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.
The actual work of a server socket is SocketImpl
performed by an instance of the class. The application can change the socket factory that creates the socket implementation to configure itself, creating a socket that is appropriate for the local firewall.
Some important methods: (see the official API bar for specific people)
ServerSocket(int port, int backlog)
Creates a server socket with the specified backlog and binds it to the specified local port number.
bind(SocketAddress endpoint, int backlog)
will be ServerSocket
bound to a specific address (IP address and port number).
accept()
Listen for and accept connections to this socket
getInetAddress()
Returns the local address of this server socket.
close()
Close the socket.
2. Look at the socket again
Class Socket
This class implements a client socket (which can also be called a "socket"). Sockets are the endpoints of communication between two machines.
The actual work of the socket is SocketImpl
performed by an instance of the class. The application can configure itself to create a socket that is appropriate for the local firewall by changing the socket factory that created the socket implementation.
Some important methods: (see the official API bar for specific people)
Socket(InetAddress address, int port)
Creates a stream socket and connects it to the specified port number for the specified IP address.
getInetAddress()
Returns the address of the socket connection.
shutdownInput()
The input stream for this socket is placed at the end of the stream.
shutdownOutput()
Disables the output stream for this socket.
close()
Close the socket.
3, the Code implementation: (Note is very full, here is not detailed more said)
Service-Side Server.java
1. Create a ServerSocket object, bind and listen to the port
2. Listening for client requests via accept
3. After the connection is established, read and write through the output input stream
4. Close Related Resources
1 ImportJava.io.BufferedReader;2 Importjava.io.IOException;3 ImportJava.io.InputStream;4 ImportJava.io.InputStreamReader;5 ImportJava.io.OutputStream;6 ImportJava.io.PrintWriter;7 ImportJava.net.ServerSocket;8 ImportJava.net.Socket;9 Ten One Public classServer { A - /** - * Socket Service side the */ - Public Static voidMain (string[] args) { - Try { -ServerSocket serversocket=NewServerSocket (8888); +SYSTEM.OUT.PRINTLN ("Service side started, waiting for client connection ..."); -Socket socket=serversocket.accept ();//listens for and accepts connections to this socket, returns a socket object + A at //based on input and output streams and client connections -InputStream Inputstream=socket.getinputstream ();//get an input stream that receives information passed by the client -InputStreamReader inputstreamreader=NewInputStreamReader (InputStream);//increase your efficiency and stream your own bytes into a character flow -BufferedReader bufferedreader=NewBufferedReader (InputStreamReader);//Join Buffer -String temp=NULL; -String info= ""; in while((Temp=bufferedreader.readline ())! =NULL){ -info+=temp; toSYSTEM.OUT.PRINTLN ("Client Connection received"); +SYSTEM.OUT.PRINTLN ("Server received client information:" +info+ ", the current client IP is:" +socket.getinetaddress (). gethostaddress ()); - } the *OutputStream Outputstream=socket.getoutputstream ();//gets an output stream that sends information to the server $PrintWriter printwriter=NewPrintWriter (OutputStream);//wrapping the output stream as a print streamPanax NotoginsengPrintwriter.print ("Hello, the server has received your information"); - Printwriter.flush (); theSocket.shutdownoutput ();//turn off the output stream + A the + //close the corresponding resource - printwriter.close (); $ outputstream.close (); $ bufferedreader.close (); - inputstream.close (); - socket.close (); the -}Catch(IOException e) {Wuyi e.printstacktrace (); the } - } Wu -}
Client Client.java
1. Create the Socket object, specify the address and port number of the server side
2. After the connection is established, read and write through the output input stream
3. Get server return information via output input stream
4. Close Related Resources
1 ImportJava.io.BufferedReader;2 Importjava.io.IOException;3 ImportJava.io.InputStream;4 ImportJava.io.InputStreamReader;5 ImportJava.io.OutputStream;6 ImportJava.io.PrintWriter;7 ImportJava.net.Socket;8 Importjava.net.UnknownHostException;9 Ten One Public classClient { A - /** - * Socket Client the */ - Public Static voidMain (string[] args) { - Try { - //creating a Socket object +Socket socket=NewSocket ("localhost", 8888); - + //based on input and output streams and server-side connections AOutputStream Outputstream=socket.getoutputstream ();//gets an output stream that sends information to the server atPrintWriter printwriter=NewPrintWriter (OutputStream);//wrapping the output stream as a print stream -Printwriter.print ("Service side Hello, I am balla_ rabbit"); - Printwriter.flush (); -Socket.shutdownoutput ();//turn off the output stream - -InputStream Inputstream=socket.getinputstream ();//gets an input stream that receives information from the server inInputStreamReader inputstreamreader=NewInputStreamReader (InputStream);//package into character stream for increased efficiency -BufferedReader bufferedreader=NewBufferedReader (InputStreamReader);//buffers toString info= ""; +String temp=NULL;//Temp Variable - while((Temp=bufferedreader.readline ())! =NULL){ theinfo+=temp; *SYSTEM.OUT.PRINTLN ("Client Receives server Send message:" +info); $ }Panax Notoginseng - //close the corresponding resource the bufferedreader.close (); + inputstream.close (); A printwriter.close (); the outputstream.close (); + socket.close (); -}Catch(unknownhostexception e) { $ e.printstacktrace (); $}Catch(IOException e) { - e.printstacktrace (); - } the - }Wuyi the}
4. Effect:
Service side:
Client:
The above code is implemented, but the client and server connection, to achieve multi-client operation, need to involve multi-threading, each received socket object to open a separate thread operation, and then with a dead loop while (true) to listen to the port on the line, continue the code to write the next article.
TCP protocol-based simple socket Communication Note (JAVA)