构建服务器之间的套接字连接:超时异常

时间:2017-05-09 08:53:48

标签: java sockets timeoutexception socket-timeout-exception

我是Java Socket编程的新手。我想要做的是在多个服务器之间建立套接字连接(模拟分布式系统)。 当我尝试使用以下Java代码执行此操作时,它会返回超时异常(其他服务器正在执行并等待接受),请帮我修复它:

// a function that sends request to the given IP and port
//myservers is an array of a class that stores IP, PORT, STATUS, Data Input and Data output streams of a connection.
public boolean request(String ip, int port, int index)
{
   try
   {
     InetSocketAddress serverSock=new InetSocketAddress(ip,port);
     Socket otherserver=new Socket();
     otherserver.connect(serverSock);
     if(otherserver.isConnected())
     {
       myservers[index].sock=otherserver;
       myservers[index].setup(); // method that makes Data streams
       myservers[index].status="active";
       return true;
      }
     else
     {
        return false;
      }
   }
   catch(Exception e)
   {
    JOptionPane.showMessageDialog(null, e.getMessage(), "Connection Error", 
    JOptionPane.ERROR_MESSAGE);
    return false;
   }
}

//function that calls the above-mentioned function in a loop is following:
public void makeConnections()
{
  int connected=0;
  for(int i=0;i<3;i++)
  {
    String a=request(myservers[i].ip,myservers[i].port,i);
    if(a.equalsIgnoreCase("success"))
    {
        connected++;
    }
   }
}

0 个答案:

没有答案