Socket plays a very important role in Android network programming.

Basic Concepts of Socket

A socket is an intermediate software abstraction layer for the communication between the application layer and the TCP/IP protocol family. It is a programming interface (API) that encapsulates the TCP/IP protocol family. From the point of view of design mode, Socket is actually a facade mode, it hides the complex TCP/IP protocol family behind the Socket interface, for the user, a simple set of interfaces is all, let the Socket to organize data to conform to the specified protocol.

Borrow the online structure diagram:

The Socket = {(IP address1:PORT PORT number), (IP address2:PORT PORT number)}Copy the code

Socke alone is useless. Only Socket programming based on certain protocols (TCP or UDP) can be used for data transmission.

Socket workflow





classification

There are two types of Socket usage:

  • Based on TCP protocol, stream socket, using stream mode to provide reliable byte stream service
  • Based on the UDP protocol, the datagram socket uses data packets to provide data packaging and sending services

Based on TCP Socket programming

The main API

Socket

A constructor

public Socket(String host, int port)
        throws UnknownHostException, IOException
Copy the code

Creates a stream socket and connects it to the specified port number on the specified host.

  • host: Host address
  • port: the port number

getInputStream

Returns the input stream to the Socket, and the user receives data.

getOutputStream

Returns the output stream of the Socket used to send data.

ServerSocket

Socket server implementation

The constructor

public ServerSocket(int port) throws IOException
Copy the code

Create a server Socket and bind it to the specified port.

  • port: the port number

accept

public Socket accept(a) throws IOException
Copy the code

Listen for and accept connections to this socket. This method blocks until a connection is established.

The sample

The service side

public class Server {
    public static void main(String[] args) throws IOException {
        / / 1. Create a ServerSocket
        ServerSocket serverSocket = new ServerSocket(8888);
        / / 2. Listen
        Socket socket = serverSocket.accept();
        System.out.println("server start listen");
        / / 3. The input stream
        InputStream is = socket.getInputStream();
        InputStreamReader reader = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(reader);
        String content = null;
        StringBuffer sb = new StringBuffer();
        while((content = br.readLine()) ! =null) {
            sb.append(content);
        }

        System.out.println("server receiver: "+ sb.toString()); socket.shutdownInput(); br.close(); reader.close(); is.close(); socket.close(); serverSocket.close(); }}Copy the code

A very simple Socket server that receives data from the client and closes the current connection. This example just shows a complete process. If a complex server-side implementation is required, Netty, Mina, or another Socket framework can be used.

The client

1. Create a client
Socket socket = new Socket("your ip".8888);
/ / 2. The output stream
OutputStream os = socket.getOutputStream();
//3. Send data
os.write("Hello world".getBytes());
System.out.println("send message");
os.flush();

socket.shutdownOutput();

os.close();
socket.close();
Copy the code

The client connects, sends a piece of data, and then closes the connection. This enables communication between the client and the server.

Socket programming based on UDP

The main API

DatagramPacket

Used to wrap incoming and outgoing data.

  • Construct receive packet
public DatagramPacket(byte[] buf,int length)
Copy the code

Used to receive packets of length.

  • Construct send packet
DatagramPacket(byte[] buf, int length,SocketAddress address)
DatagramPacket(byte[] buf, int length, InetAddress address, int port)
Copy the code

Used to send packets of length to the specified port number on the specified host.

DatagramSocket

A socket used to send and receive datagram packets.

A constructor

// Create a datagram socket and bind it to the specified port on the localhost
DatagramSocket(int port)  

// Create a datagram socket and bind it to the specified local address
DatagramSocket(int port, InetAddress laddr)     
Copy the code

To send data

void send(DatagramPacket p)
Copy the code

The DatagramPacket contains information indicating the data to be sent, its length, the IP address of the remote host, and the port number of the remote host

Receive data

void receive(DatagramPacket p) 
Copy the code

When this method returns, the buffer of the DatagramPacket is filled with the received data.

The sample

The service side

public class UDPServer {
    public static void main(String[] args) throws IOException {
        byte[] buf = new byte[1024];
        // receive
        // 1.create
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        // 2.create udp socket
        DatagramSocket socket = new DatagramSocket(8888);
        // 3. receive start
        socket.receive(packet);
        // 4. receive data
        System.out.println("sever: " + new String(buf, 0, buf.length));

        // send
        DatagramPacket p = newDatagramPacket(buf, buf.length, packet.getAddress(), packet.getPort()); socket.send(p); socket.close(); }}Copy the code

The client

// send
InetAddress address = InetAddress.getByName("your ip");
//1.create packet
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, 8888);
//2.create socket
DatagramSocket socket = new DatagramSocket();
//3.send data
socket.send(packet);
// receive
//1.create packet
final byte[] bytes = new byte[1024];
DatagramPacket receiverPacket = new DatagramPacket(bytes, bytes.length);
socket.receive(receiverPacket);
System.out.println("client: " + new String(bytes, 0, bytes.length));

socket.close();
Copy the code

Both client-side and server-side implementations are relatively simple.

About Socket programming, it is good to introduce, this article is just the beginning, the most important or have to go to the project practice.

reference

  • Android: This is a very detailed Socket usage walkthrough
  • Scoket programming