java - 让服务器套接字在每次迭代中等待客户端套接字

标签 java sockets while-loop timeout

我启动服务器程序,它只等待客户端 30 秒。它在第一次迭代中工作正常,并且在剩余迭代中不等待。任何建议。

这里

minLinkWt() sets the index. 

但是它在程序中保持不变。

import java.sql.*;
import java.net.*;
import java.lang.*;
class Democ{
 int index,port,min=100;
ServerSocket ss=null;
Socket s=null;

void begin(){
int av=0;boolean b=false;
    minLinkWt();
    while(!b){
    av=checkStatus(index);
    if(av==1){b=true;}
             }
        if(av==1)
        Connect();
        else
        System.out.println("No Routers Available");
}
 void Connect()
    {
    System.out.println("Enter the Message to send to clients::");
    try{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String msg=br.readLine();
    PrintStream ps=new PrintStream(s.getOutputStream());
    ps.println(msg);
    }catch(Exception e){e.printStackTrace();}
    }
void callSwitch(int index_formal)
{
switch(index_formal)
{
case 1:
port=2000;
break;
case 2:
port=2001;
break;
case 3:
port=2002;  
break;
case 4:
port=2003;
break;
default:
System.out.println("No Routers in Available");
}
}

 int checkStatus(int index_formal){
            try
            {
             ss=new ServerSocket(port);
            ss.setSoTimeout(30000);     
             s=ss.accept();             
            }catch(InterruptedIOException e){
            System.out.println("Cannot connect through Router1 Waiting for Router2");}
            catch(Exception g){g.printStackTrace();}    
            if(s==null)
            return 0;
            else 
            return 1;
    }
class DemoCopy{
public static void main(String s[])
{
Democ obj=new Democ();
obj.begin();
}
}

因此,在每次迭代中,服务器必须等待客户端,但它不会等待。 我得到的输出为

hello
hello
hello
hello
min is6
AT index2
Cannot connect through Router1 Waiting for Router2
No Routers Available

最佳答案

看起来 begin() 中的“index”可以是数组的索引,因此您想检查服务器套接字端口的状态,从 0 到 x 或其他。

也许您应该发布更多源代码,但看起来您在 checkStatus() 中使用单个端口值,这意味着 ServerSocket 每次都会绑定(bind)相同的端口。

第一次迭代时没问题,因为服务器套接字未绑定(bind)在任何端口,但在第一次迭代结束时,您根本没有关闭服务器套接字。

因此,服务器套接字仍然绑定(bind)在给定端口,并且使用相同端口号创建新的 ServerSocket 将失败,因为它已经绑定(bind),并且除非先关闭它,否则无法再次绑定(bind)它。

你应该使用单个ServerSocket,一旦serverSocket.accept()返回socket,那么你可以将它存储到数组中并经常检查它的状态。或者也许你可以每次都区分端口号,让客户端每次连接不同的端口也可以,但我不认为这就是你想要做的。

关于java - 让服务器套接字在每次迭代中等待客户端套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21967500/

相关文章:

java - 如何在 linux 中只获取进程的监听端口

java - 504 生成 Excel 文件时网关超时

sockets - 将 nginx 位置重定向/重写到不带前缀的 .sock 文件

c - 错误: ‘struct msghdr’ has no member named ‘msg_iov’

python - Python 中的 For 循环与多处理

java - onPostExecute Looper AsyncTask

java - 如何在jsp中使用enumset.contains?

sockets - 创建多个 ZeroMQ 套接字的开销是多少?

MySQL 存储例程错误

java - 使 Java 程序循环直到输入 x?