gpt4 book ai didi

Java - 读完后让套接字客户端保持 Activity 状态

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:05:01 25 4
gpt4 key购买 nike

我对 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();
}
}
}

最佳答案

accept() 返回时,服务器将收到一个套接字,只要该套接字没有关闭,连接就会保持打开状态。

所以当你第一次运行应用程序,然后关闭服务器然后第二次运行它时,我认为连接会断开,你必须重新初始化它。

isConnected() 方法会给您一个错误的结果,因为如果您没有在客户端明确关闭套接字,它将始终返回 true

如果您想确定,您可以运行一次客户端-服务器连接,然后关闭服务器,重新启动它,然后尝试从服务器读取/写入服务器。如果连接断开,读取结果将返回 -1,写入将返回 IOException

关于Java - 读完后让套接字客户端保持 Activity 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23135623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com