[英]Java: how to connect to different servers from a client socket on one port?
A TCP connection is identified by four elements(maybe protocol included): client port, client address, server port, server address. TCP连接由四个元素(可能包括协议)标识:客户端端口,客户端地址,服务器端口,服务器地址。 So it's possible for a client with one port to connect to multiple different servers.Because they're different TCP connections.
因此,具有一个端口的客户端可能会连接到多个不同的服务器,因为它们是不同的TCP连接。
Here's my demo: a local client on port 9999 conncecting to two local servers on port 12345 and port 12346. But the code isn't correct. 这是我的演示:端口9999上的本地客户端连接到端口12345和端口12346上的两个本地服务器。但是代码不正确。
Can anybody help me? 有谁能够帮助我? Tell me how to correct it, please.(not use SO_REUSEPORT or fork)
请告诉我如何更正。(请勿使用SO_REUSEPORT或fork)
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketTest {
public static void main(String[] args) throws IOException {
startServer(12345);
startServer(12346);
Socket socket = new Socket();
socket.bind(new InetSocketAddress(9999));
System.out.println("client: " + socket.getLocalSocketAddress().toString());
startClient(socket, 12345);
startClient(socket, 12346);
}
public static void startClient(Socket socket, int port) {
(new Thread() {
@Override
public void run() {
try {
// Problem: connect() can be called only once
socket.connect(new InetSocketAddress(port));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public static void startServer(int port) {
new Thread() {
@Override
public void run() {
ServerSocket ss;
try {
ss = new ServerSocket(port);
System.out.println("listen on: " + ss.getLocalSocketAddress());
while (true) {
Socket s = ss.accept();
System.out.println("accept from: " + s.getRemoteSocketAddress());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
You can bind 2 different sockets to the same local port (that is what SO_REUSEADDR is made for), but one single socket can only be connected to one single destination. 您可以将2个不同的套接字绑定到同一个本地端口(这就是SO_REUSEADDR的用途),但是一个单独的套接字只能连接到一个单独的目的地。
If you want to send one single message, and you want that message to be received by two servers, then you need multicast. 如果要发送一条消息,并且希望该消息被两台服务器接收,则需要多播。 multicast can only use UDP (not TCP) and one of the special multicast addresses (224.0.0.0 to 239.255.255.255) that isn't listed as reserved by IANA.
多播只能使用UDP(非TCP)和IANA未列出为保留的特殊多播地址之一(224.0.0.0至239.255.255.255)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.