Java服务器使用套接字连接到其他服务器

huangapple go评论86阅读模式
英文:

Java server connect to other server using sockets

问题

以下是翻译好的内容:

我有一个项目,需要构建一个系统,其中多个服务器彼此通信以响应客户端。

我可以使客户端与服务器通信,但是我在让服务器之间启动连接方面遇到问题。

在下面的代码中,您可以看到我有一个包含所有服务器IP的列表。对于每个IP,当前服务器都会尝试与其他服务器建立连接。您还可以看到服务器在这些情况下等待连接,也就是来自其他服务器的连接。

@Override
public void run() {
    // 尝试与服务器建立连接
    for (String serverIp : servers) {
        System.out.println("尝试与" + serverIp + "建立连接");
        try {
            Socket clientSocket = new Socket(serverIp, this.port);
            this.clientPool.submit(new ClientThread(clientSocket, this.streamHandler));
        } catch (Exception e) {
            System.out.println("错误");
        }
        System.out.println("已连接" + serverIp);
    }
    // 接收其他服务器的连接
    // 在这种情况下,我们调用客户端连接到其他服务器
    try (ServerSocket serverSocket = new ServerSocket(port)) {
        System.out.println("等待客户端连接...");
        while (true) {
            Socket clientSocket = serverSocket.accept();
            this.clientPool.submit(new ClientThread(clientSocket, this.streamHandler));
        }
        // serverSocket.close();
    } catch (IOException e) {
        Configuration.printError("启动服务器时出错", e);
    }
}

问题是,服务器需要尝试与其他服务器建立连接,并等待其他服务器的连接。在收到新连接后,它需要停止尝试与相应的服务器建立连接,或者如果服务器成功尝试与其他服务器建立连接,则需要停止接受来自该服务器的新连接。

关于如何使用套接字来实现这一点,您有什么建议吗?

英文:

I have a project where I have to build a system where multiples server communicate between each other to respond to clients.

I can make the client communicate with the server but I'm having problems on making the servers start a connection between them.

In the code below you can see that I have a list with the ip's of all the server. For each ip the current server tries to connect with the other server. You can also see that the server wait's for connections, in these case, connections from the other servers.

@Override
public void run() {
	// Trying to connect with server
	for (String serverIp : servers) {
		System.out.println("Trying to connect with " + serverIp);
		try {
			Socket clientSocket = new Socket(serverIp, this.port);
			this.clientPool.submit(new ClientThread(clientSocket, this.streamHandler));
		} catch (Exception e) {
			System.out.println("Error");
		}
		System.out.println("Connected with " + serverIp);
	}
	// Receiving connections from other servers
	// In these case we call client to the other server
	try (ServerSocket serverSocket = new ServerSocket(port)) {
		System.out.println("Waiting for clients to connect...");
		while (true) {
			Socket clientSocket = serverSocket.accept();
			this.clientPool.submit(new ClientThread(clientSocket, this.streamHandler));
		}
		// serverSocket.close();
	} catch (IOException e) {
		Configuration.printError("Error starting server", e);
	}
}

The problem is that the server needs to try to connect with the other servers and wait for connections from the other servers. And after receiving a new connection it needs to stop trying to connect to the correspondent server or if the server have success trying to connect with the other server, it needs to stop receiving new connections from that server.

Any suggestions on how to implement this with sockets?

答案1

得分: 1

看起来你试图分步完成这个过程,首先所有服务器都尝试连接其他服务器,但没有服务器已经开始接受连接。在clientSocket连接到服务器之后,你开始接受连接。听起来这可能会导致死锁。

你知道每个服务器必须从其他服务器接受连接。你还知道每个服务器需要初始化与其他服务器的连接。

你必须在两个不同的线程中进行接受连接初始化连接,或者你应该使用异步/事件驱动模型并管理事件循环。

在接收到新连接后,它需要停止尝试连接到对应的服务器,或者如果服务器成功尝试与另一台服务器连接,则需要停止从该服务器接收新连接。

在这里,你希望避免竞争条件。如果每个服务器在尝试连接到其他服务器之前等待X时间,这样做会更容易。这个X应该是启动时的随机延迟。例如,服务器A在连接之前等待5秒,服务器B等待1秒,服务器C在连接之前等待13秒。但是由于服务器A已经与那些服务器建立了连接,所以服务器B和C将不会初始化任何连接。

英文:

It seems like you try to do this in steps, first all servers try to connect to the others, but no server have started to accept connections yet. And after the clientSocket has connected to servers, you then start to accept connections. It sounds like this can lead to a deadlock.

You know that each server must accept connections from other servers. You also know that each server need to initiate connections to the other servers.

You must either accept connections and initiated connections in two different threads, or you should use an asynchronous/event driven model and manage an event loop.

>And after receiving a new connection it needs to stop trying to connect to the correspondent server or if the server have success trying to connect with the other server, it needs to stop receiving new connections from that server.

Here you want to avoid a race. This is easiest to do if each server wait X time before trying to connect to the other servers. This X should be a random delay from startup. E.g. server A waits 5 seconds before connecting, server B waits 1 second, and server C waits 13 seconds before connecting. But server B and C will not initiated any connections since server A already have established connections to those servers.

huangapple
  • 本文由 发表于 2020年10月10日 16:23:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64291425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定