gpt4 book ai didi

Java Socket 处理客户端断开连接

转载 作者:行者123 更新时间:2023-11-30 07:44:32 31 4
gpt4 key购买 nike

我正在尝试制作一个聊天程序。我遇到的问题是 EchoThread 中的循环始终认为连接是正确的。我尝试过使用 if(s.isConnected() == false)但这也不起作用,我也尝试这样做 if(s.isClosed() == true)如果您能提供帮助,提前感谢您。这是我的代码

import java.io.*;
import java.net.*;
import java.util.ArrayList;

public class server {
public ObjectInputStream input;
public ServerSocket server;
public Socket s;
public ObjectOutputStream output;
public ArrayList<ObjectOutputStream> outputs = new ArrayList<ObjectOutputStream>();
public ArrayList<Socket> users = new ArrayList<Socket>();
public class Accept implements Runnable {
public void run() {
try {
server = new ServerSocket(55555, 100);
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
try {
s = server.accept();
new EchoThread(s).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class EchoThread extends Thread {
private Socket s1;
public EchoThread(Socket s) throws IOException {
this.s1 = s;
}
public void run() {
users.add(s1);
try {
outputs.add(new ObjectOutputStream(s1.getOutputStream()));
newUser();
} catch (IOException e) {
System.out.println("Error 2");
}
while(s1.isConnected() == true) {
// loops until socket looses connection
}
System.out.println("Disconnected");
}
}
public class check implements Runnable {

public void run() {
}

}
public void newUser() {
try {
for(ObjectOutputStream o: outputs) {
o.writeObject(s.getInetAddress() + " Connected");
}
} catch (IOException e1) {
System.out.println("Error 21");
}
}
server() throws IOException {
Thread t = new Thread(new Accept());
t.start();
Thread ch = new Thread(new check());
ch.start();
}
public static void main(String[] args) throws IOException {
new server();
}
}

最佳答案

您必须阅读此内容,您必须使用 read() 方法检查它是否返回 -1

https://stackoverflow.com/a/10241044/964152

关于Java Socket 处理客户端断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34112730/

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