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();
}
}