【问题标题】:how do I communicate between two servers using sockets java我如何使用套接字java在两台服务器之间进行通信
【发布时间】:2015-04-29 04:33:56
【问题描述】:

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

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

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


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

【问题讨论】:

    标签: java sockets server


    【解决方案1】:

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

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

    你不应该需要这个循环:

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

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

    【讨论】:

    • 如何等待服务器 #1 启动并查看它是否从服务器 #0 连接??
    • 使用“catch”来检测连接失败的时间。然后,等待几秒钟,然后重试连接。您可能还想检查您重试了多少次,所以它可以在 3 次尝试(或其他)后放弃。
    • 非常感谢,我在 catch 块中放了一个简单的“i--”语句,它起作用了。再次感谢您。
    • 没问题,祝您项目顺利!既然我已经帮助回答了这个问题,您介意将其标记为已接受的答案吗? :D
    猜你喜欢
    • 2023-03-07
    • 2011-02-20
    • 2012-07-06
    • 2013-06-24
    • 2013-01-08
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 2020-05-28
    相关资源
    最近更新 更多