Android connects multiple tcp servers in one thread

Posted by ahmed17 on Sun, 03 May 2020 18:07:49 +0200

In general, when our client starts tcp to connect to the server, it's a connection thread, so it's easy to write code

public class SocketTcpClient implements Runnable {

    private final String ip;
    private Socket socket;

    public SocketTcpClient(String ip) {
        this.context = context;
        this.ip = ip;
    }

    @Override
    public void run() {
        try {
            socket = new Socket(ip, 5246);
            OutputStream out = socket.getOutputStream();
            out.write("Hello World".getBytes());
            while (true) {
                InputStream in = socket.getInputStream();
                byte[] buff = new byte[1024];
                int length = in.read(buff);
                //Data received
                String data = new String(buff, 0, length);

            }
        } catch (Exception e) {
            e.printStackTrace();
    }
}

You only need to start this thread to use, so you can always receive the data sent from the server. If you have more than one server to connect to, just set a for loop outside;
In this way, if there are too many connections and too many threads, it will be a waste of resources.

   new Thread(new SocketTcpClient("192.168.0.252")).start();

Now let's go back to what we need to say in this article: one thread connects multiple tcp, just modify the client

public class SocketTcpClient {

    private Socket socket;
    private byte[] buff = new byte[1024];

    SocketTcpClient(String ip, int port) {
        try {
            //Create a tcp connection first
            socket = new Socket(ip, port);
            OutputStream out = socket.getOutputStream();
            out.write("Hello World".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Loop data
     */
    public void run() {
        try {
            InputStream in = socket.getInputStream();
            int length = in.read(buff);
            String data = new String(buff, 0, length);
            System.out.println(data.replace("\n", ""));
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}

Initializing the socket tcp connection using the constructor
Write a run() function to get the data sent by the server
The next point is to start the thread and continue to receive data

Starting multiple tcp clients with one thread

public class Test {

    public static int port1 = 8271;
    public static int port2 = 8272;
    public static int port3 = 8273;

    public static List<SocketTcpClient> clients = new ArrayList<>();

    public static void main(String[] args) {
        //Simulate three servers
        new Thread(new SocketTcpServer(port1)).start();
        new Thread(new SocketTcpServer(port2)).start();
        new Thread(new SocketTcpServer(port3)).start();

        //Client opens a thread to connect three tcp servers
        new Thread(() -> {
            //Open three clients to establish three tcp connections
            clients.add(new SocketTcpClient("127.0.0.1", port1));
            clients.add(new SocketTcpClient("127.0.0.1", port2));
            clients.add(new SocketTcpClient("127.0.0.1", port3));

            while (true) {
                for (SocketTcpClient client : clients) {
                    client.run();
                }
            }
        }).start();
    }
}

This can be implemented temporarily, but there will be problems if there are too many connections; at this time, you need to use Java non blocking IO (NIO).

Demo download

Topics: socket Java