Java 使服务器套接字在每次迭代中等待客户端套接字
我启动服务器程序,它只等待客户端30秒。它在第一次迭代中工作正常,在剩余的迭代中不等待。有什么建议吗 这是Java 使服务器套接字在每次迭代中等待客户端套接字,java,sockets,while-loop,timeout,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 a
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每次都将绑定到同一个端口
在第一次迭代时这是可以的,因为服务器套接字并没有绑定到任何端口,但在第一次迭代结束时,您根本并没有关闭服务器套接字
所以服务器套接字仍然绑定在给定的端口,创建具有相同端口号的新ServerSocket将失败,因为它已经绑定,除非先关闭它,否则无法再次绑定它
您应该使用单个ServerSocket,一旦ServerSocket.accept()返回socket,就可以将其存储到数组中并经常检查其状态。或者您可以每次区分端口号,让客户端每次连接不同的端口也可以工作,但我不认为这是您想要做的。我已将服务器编程为在同一程序中侦听不同的端口号。当服务器第一次侦听时,请说出端口号2000,然后再次在我的代码中尝试更改端口号,然后出现连接重置异常。因此我考虑了上面的代码。您能建议我在什么时候进行在这种情况下,我是否应该打开和关闭连接插座以获得等待时间。等待。。。若您将服务器编程为每次侦听不同的端口,那个么如何让客户端知道哪些端口可用?基于您提出的“使服务器套接字在每次迭代中等待客户端套接字”的问题,您只需打开一个具有特定端口号的服务器套接字一次,并在while循环中调用serverSocket.accept(),这样服务器就会建立连接并返回连接到客户端的套接字对象。因此,这就像//创建具有特定端口号的服务器套接字(仅一次)而(true){//socket sock=serverSocke.accept();//从套接字读取数据,可能的读取应该在新创建的线程中,以便服务器端可以保持传入的客户端套接字连接。}