【问题标题】:Making Server Socket to wait for Client Socket in each iteration使服务器套接字在每次迭代中等待客户端套接字
【发布时间】:2014-02-23 11:17:44
【问题描述】:

我启动服务器程序,它只等待客户端 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

【问题讨论】:

    标签: java sockets while-loop timeout


    【解决方案1】:

    begin()中的“index”好像可以是数组的索引,所以要检查Server socket port form 0 to x之类的状态。

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

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

    所以服务器套接字仍然绑定在给定端口,创建具有相同端口号的新服务器套接字将失败,因为它已经绑定,除非你先关闭它,否则你不能再次绑定它。

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

    【讨论】:

    • 我已经将服务器编程为在同一个程序中侦听不同的端口号。当它第一次侦听端口号 2000 时,如果在我的代码中我尝试更改端口号然后我得到连接重置异常。所以我想到了上面的代码。
    • 你能建议我在什么时候打开和关闭连接套接字以实现在这种情况下的等待时间。
    • 等等...如果你编程服务器每次监听不同的端口,你将如何让客户端知道哪些端口可用?根据您的问题“使服务器套接字在每次迭代中等待客户端套接字”,您应该只打开一个具有特定端口号的服务器套接字一次,并在 while 循环中调用 serverSocket.accept(),这样服务器就会建立连接并返回连接到客户端的套接字对象。
    • 所以,就像 // 创建具有特定端口号的服务器套接字(仅一次) while (true) { // Socket sock = serverSocke.accept(); // 从套接字读取数据,可能的读取应该在新创建的线程中,以便服务器端可以保持传入的客户端套接字连接。 }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2017-12-10
    • 2011-11-15
    • 1970-01-01
    • 2017-02-25
    • 2014-11-05
    • 1970-01-01
    相关资源
    最近更新 更多