gpt4 book ai didi

java - 如何使用java套接字在两个服务器之间进行通信

转载 作者:行者123 更新时间:2023-12-01 11:36:27 26 4
gpt4 key购买 nike

我正在尝试在此处连接两台服务器

以下是我的代码,它将在两台服务器上运行

public class Node {

/**
* @param args the command line arguments
*/

private int nodeID;
private int port;
private ServerSocket nodeSock;
private int maxNodes = SysInfo.maxNodes;
private Socket otherSock;
private PrintWriter ostream;
private BufferedReader in;
private int connectedNodeID;
private HashMap<Integer, Socket> socks;
private HashMap<Socket, PrintWriter> ostreams;
private boolean isPrimary;


public Node(int nodeID, boolean isPrimary){
this.nodeID = nodeID;
this.port = SysInfo.nodePorts[nodeID];
this.isPrimary = isPrimary;
socks = new HashMap<Integer, Socket>();
ostreams = new HashMap<Socket, PrintWriter>();
System.out.println("current node #"+this.nodeID+" : ");
try{
//nodeSock = new ServerSocket(SysInfo.nodePorts[nodeID]);
nodeSock = new ServerSocket(this.port,0,InetAddress.getByName("127.0.0.1"));
}catch(IOException e){
e.printStackTrace();
}

makeSystemReady();
}
private void makeSystemReady() {
System.out.println("Making the system ready");
System.out.println(nodeSock.getLocalSocketAddress()+ ";"+nodeSock.getInetAddress()+";"+nodeSock.getLocalPort());
for(int i = 0 ; i < SysInfo.maxNodes ; i++ ){
if(i == nodeID)
continue;
// this.connectToNode(SysInfo.nodePorts[i], i);
try {
System.out.println("waiting for connection to node #"+i+" to be established");
Socket s = new Socket(InetAddress.getByName("127.0.0.1"), SysInfo.nodePorts[i]);
//socks.put(port, s);
while(!(s.isConnected()));
System.out.println("node #"+nodeID+" connected to other node#"+i);

} catch (IOException ex) {
/* ignore */
}
}
}

我正在尝试检查两个节点是否已连接,然后才继续下一阶段(即,如果两个服务器都已启动并运行,我只会开始实际通信。)

但我在这里没有得到正确的结果。我得到的输出如下......

节点 0 处的输出...

current node #0 :

使系统准备就绪

/127.0.0.1:20000;/127.0.0.1;20000

等待建立与节点#1的连接

<小时/>

并在节点1处输出......

current node #1 : 

使系统准备就绪

/127.0.0.1:20001;/127.0.0.1;20001

等待建立与节点 #0 的连接

节点#1连接到其他节点#0

<小时/>

在一个节点上它显示已连接,而在另一节点上则没有显示任何内容。请帮助我,我哪里出错了。

最佳答案

您尝试在节点 1 启动之前连接到节点 1。连接失败并引发异常,您可以忽略该异常。如果您将“/*ignore*/”更改为“ex.printStackTrace();”,您会发现这种情况正在发生。

如果您不知道如何处理异常,请不要忽略它,因为这样的事情每次都会发生。

你不应该需要这个循环:

while(!(s.isConnected()));

套接字在“new Socket”完成之前建立连接,因此在这里检查连接是没有意义的。更糟糕的是,如果它连接然后立即断开连接,您将陷入无限循环。

关于java - 如何使用java套接字在两个服务器之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29934437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com