如何使用套接字 Java 在两台服务器之间进行通信



我正在尝试在这里连接两台服务器

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

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();",您会发现这种情况正在发生。

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

您不需要此循环:

而(!(s.isConnected()));
套接字

在"新套接字"完成之前建立连接,因此在此处检查连接毫无意义。更糟糕的是,如果它连接然后立即断开连接,您将陷入无限循环。

最新更新