我对Java中的socket还不是很熟悉,但这是我的问题:
我编写了一个客户端线程类,将请求连接到由另一个应用程序创建的服务器(因此我没有为服务器类创建一个类)。基本上,该应用程序将传输一定数量的字节并关闭套接字的服务器端。我已经完全能够接收和处理这些字节。
我的问题是,客户端套接字是否可以被告知“等待”,直到来自相同地址/端口的另一个连接可用,并继续读取字节?(实质上,我运行应用程序,它读取字节并完成,然后我再次运行应用程序,客户端仍然能够读取)
以下是我的客户端线程代码:
我编写了一个客户端线程类,将请求连接到由另一个应用程序创建的服务器(因此我没有为服务器类创建一个类)。基本上,该应用程序将传输一定数量的字节并关闭套接字的服务器端。我已经完全能够接收和处理这些字节。
我的问题是,客户端套接字是否可以被告知“等待”,直到来自相同地址/端口的另一个连接可用,并继续读取字节?(实质上,我运行应用程序,它读取字节并完成,然后我再次运行应用程序,客户端仍然能够读取)
以下是我的客户端线程代码:
public class ClientThread extends Thread{
private Socket soc;
private InputStream in;
private String host;
private int port;
public ClientThread(String host, int port)
{
this.host = host;
this.port = port;
soc = null;
in = null;
}
public boolean connectToServer()
{
try {
soc = new Socket(host, port);
in = new BufferedInputStream(soc.getInputStream());
System.err.println("Connection accepted: "+soc);
return true;
} catch (UnknownHostException e) {
System.err.println("Unable to determine IP of host: "+host+".");
return false;
} catch (SocketException e) {
System.err.println("Error creating or accessing the socket.");
return false;
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: "+host+".");
return false;
}
}
public boolean disconnectFromServer()
{
try {
if(in != null)
in.close();
if(soc != null && soc.isConnected()) {
soc.close();
soc = null;
System.err.println("Connection successfully closed!");
}
return true;
} catch (Exception e) {
System.err.println("Exception: "+e);
return false;
}
}
@Override
public void run() {
try {
int sz = 0;
byte[] tmp = new byte[25];
while(true)
{
if(sz == -1) {
sz = 0;
}
sz += in.read(tmp, sz, 25-sz);
System.out.println(sz);
if(sz == 25) {
tmp = new byte[25];
for(byte b: tmp)
System.out.print(b);
sz = 0;
Thread.sleep(500);
}
}
} catch (SocketException e) {
System.err.println("Connection closed abruptly.");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: "+host+".");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Thread
,使用我在答案中描述的方法定期检查连接(只需读取或写入,我猜读取可能是最简单的),当连接丢失时,调用一个打开连接的方法。 - JNevens