【发布时间】:2014-06-01 20:54:45
【问题描述】:
我对 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();
}
}
}
【问题讨论】: