Java套接字处理客户端断开连接

时间:2015-12-06 00:50:20

标签: java sockets

我正在尝试制作聊天程序。我遇到的问题是我在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();
}
}

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

while(s1.isConnected() == true) {

这不是一个有效的循环。 isConnected()是正确的,因为你接受了套接字,并且之后它并没有神奇地变为假。当客户端断开连接时,您将从您正在调用的任何读取方法获得适当的流指示结束。