【发布时间】: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
在一个节点上它显示它已连接,而在另一个节点上它没有显示任何东西。 请帮助我这里哪里出错了。
【问题讨论】: