有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何使用javasocket在两台服务器之间进行通信

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

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

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;两万

正在等待建立到节点#1的连接


和节点1处的输出

current node #1 : 

准备好系统

/127.0.0.1:20001/127.0.0.1;20001

正在等待建立到节点#0的连接

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


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


共 (1) 个答案

  1. # 1 楼答案

    您尝试在节点1启动之前连接到节点1。连接失败并引发您忽略的异常。如果将“/*忽略*/”更改为“例如printStackTrace();”,你会发现这正在发生

    如果你不知道如何处理异常,千万不要忽视它,因为这样的事情每次都会发生

    你不应该需要这个循环:

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

    插座在“新插座”完成之前连接,所以在这里检查连接是没有意义的。更糟糕的是,如果它连接,然后立即断开,你将陷入一个无限循环