我有点新在Java套接字,但这里的是我的问题:爪哇 - 保持一个套接字客户端活着读完
我写了一个客户端线程类,将请求连接到服务器,创建由另一个应用程序(因此我没有为服务器类制作的类)。基本上,这个应用程序将传输一定数量的字节并关闭套接字的服务器端。我已经完全能够接收和处理这些字节。
我的问题是可以在客户端插座被告知“等待”从同一地址/端口的另一连接可用,然后继续读取的字节? (从本质上说,我运行应用程序时,它读取的字节数和完成了,那么我再次运行应用程序,并在客户端将仍然能够读取)
这里是我的客户线程代码:
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
可能工作。但如果它不太麻烦,我还有另一个问题。假设我在应用程序传输了所有数据之前手动断开了我的客户端。然后,我想重新连接我的客户端,以完成其余数据的阅读。那可能吗?我有TCPview打开,它说,断开客户端后,应用程序的套接字仍在侦听。 –