The example of this article briefly describes the implementation method of Socket communication in Android. The specific content is as follows:
1. Overview of socket communication
In layman's terms, socket is the cornerstone of communication and the basic operating unit of network communication that supports the TCP/IP protocol. It is an abstract representation of the endpoint in the network communication process and contains five types of information necessary for network communication: the protocol used for connection, the IP address of the local host, the protocol port of the local process, the IP address of the remote host, and the protocol of the remote process. port.
When the application layer communicates data through the transport layer, TCP will encounter the problem of providing concurrent services to multiple application processes at the same time. Multiple TCP connections or multiple application processes may need to transmit data through the same TCP protocol port. In order to distinguish different application processes and connections, many computer operating systems provide socket (Socket) interfaces for applications to interact with the TCP/IP protocol. The application layer can use the Socket interface with the transport layer to distinguish communications from different application processes or network connections to implement concurrent services for data transmission.
In a word, socket is an encapsulation of the TCP/IP protocol.
2. Steps to use Socket (client):
1. Establish Socket (Tcp) connection
It is quite easy to establish a Socket connection in Java, which can be achieved using the Socket class provided by the class library.
Socketclient=null; //Indicates client client=newSocket("localhost",5000);
2. Send data
PrintStreamout=newPrintStream(socket.getOutputStream()); //PrintStream is the most convenient for sending data
3. Receive return information
buf=newBufferedReader(newInputStreamReader(socket.getInputStream())); // Complete the one-time reception and read the input stream of the Socket, and read the return information in it
4. Close Socket
Socket.close();
3. Supplement:
Socketsever side (non-multi-threaded implementation) ServerSocketserver=null; //Define ServerSocket class Socketclient=null; //Indicates client PrintStreamout=null; //Print stream output is most convenient server=newServerSocket(8888); //The server is on port 8888 Listen on System.out.println("The server is running and waiting for the client to connect."); client=server.accept(); //Get the connection, the program enters the blocking state Stringstr="helloworld"; //Indicates the information to be output out=newPrintStream(client.getOutputStream());out.println(str); //Output information to the client client. close();server.close();