An overview of Socket communication in Android

  • 2020-04-01 03:24:22
  • OfStack

This paper briefly describes the implementation method of Socket communication in Android, the specific content is as follows:

An overview of socket communication

Generally speaking, socket is the cornerstone of communication, which is the basic operation unit of network communication that supports TCP/IP protocol. It is an abstract representation of an endpoint in the process of network communication. It contains five kinds 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 port of the remote process.

When the application layer communicates data through the transport layer, TCP encounters the problem of concurrently serving multiple application processes. Multiple TCP connections or multiple application processes may need to transfer data over the same TCP protocol port. To distinguish between different application processes and connections, many computer operating systems provide a Socket interface for applications to interact with the TCP/IP protocol. The application layer and the transport layer can distinguish the communication from different application process or network connection through the Socket interface, and realize the concurrent service of data transmission.

In a word, socket is the encapsulation of TCP/IP protocol.

Ii. Steps of using Socket (client) :

1. Establish Socket (Tcp) connection

Establishing Socket connections in Java is fairly easy, using the Socket classes provided by the class library.


Socketclient=null; //Presentation client
client=newSocket("localhost",5000);

2. Send data


PrintStreamout=newPrintStream(socket.getOutputStream()); //PrintStream is the most convenient way to send data

3. Receive returned information


buf=newBufferedReader(newInputStreamReader(socket.getInputStream()));; //The input stream of the Socket is read in one pass and the return message is read out

4. Close the Socket


Socket.close();

Iii. Supplement:


Socketsever End (non-multithreaded implementation) 
ServerSocketserver=null; //Define the ServerSocket class
Socketclient=null; //Presentation client
PrintStreamout=null; //Print stream output is most convenient
server=newServerSocket(8888); //The server is listening on port 8888
System.out.println(" The server is running, waiting for the client to connect. ");
client=server.accept(); //Get a connection, the program into the blocking state
Stringstr="helloworld"; //Represents the information to be output
out=newPrintStream(client.getOutputStream());
out.println(str); //Output information to the client
client.close();
server.close();

Related articles: