从服务器端列表中删除不正确的用户

时间:2019-06-14 13:05:35

标签: java sockets server

我有一个用于研究的小型原始服务器和客户端。 这里有一段我​​的服务器代码:

 public class Connector implements Runnable, SocketListener {

    private Socket socket;
    private ServerSocket serverSocket;
    private List<ServerSideClient> clients = new LinkedList<>();
    private boolean triger;

    public Connector(ServerSocket serverSocket) {
        this.serverSocket = serverSocket;

    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.println("Waiting for clients..");
                triger = true;
                socket = serverSocket.accept();
                System.out.println("Client connected");
                ServerSideClient client = createClient();
                client.setConnection(true);
                client.startListeningClient();

                clients.add(client);

                new Thread(() -> {
                    socketIsClosed(client);
                }).start();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private ServerSideClient createClient() {
        return new ServerSideClient(socket);
    }


    @Override
    public synchronized void socketIsClosed(ServerSideClient client) {
        while (triger == true) {
            if (client.isConnected() == false) {
                triger = false;
                clients.remove(client);
                System.out.println("Client was removed " + clients.size());
            }
        }
    }
 }

在这里,我们等待新的客户端,然后创建客户端实例并将其添加到LinkedList。在服务器端的实例中,我们等待来自客户端的信息并在单独的线程上发送答案。但是,当客户端关闭与服务器的连接时,socketIsClosed()方法应从集合中删除当前客户端引用。但是当客户端断开连接时,我什至没有从System.out.println("Client was removed " + clients.size());方法中注销socketIsClosed(ServerSideClient client)

客户代码:

public class Client {

    private final String HOST = "localhost";
    private final int PORT = 1022;
    private InputStream inputStream;
    private OutputStream outputStream;
    private BufferedReader bufferedReader;
    private Socket socket;

    private boolean connection;

    public Client() throws IOException {
        socket = new Socket();
        socket.connect(new InetSocketAddress(HOST, PORT));
        inputStream = socket.getInputStream();
        outputStream = socket.getOutputStream();
        bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    }


    public static void main(String[] args) {
        Client client = null;
        try {
            client = new Client();
            client.work();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void work() {
        connection = true;
        listenForConsoleInput();
        receiveAnswerFromServer();
    }

    private void listenForConsoleInput() {
        new Thread(() -> {

            while (connection == true) {
                String requset = null;
                try {

                    requset = bufferedReader.readLine();
                    if (requset.equals(".")) {
                        closeConnection();
                        return;
                    } else {
                        sendRequest(requset);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }

    private void sendRequest(String request) {
        try {
            outputStream.write(request.getBytes());
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void receiveAnswerFromServer() {
        new Thread(() -> {
            while (connection == true) {
                byte[] data = new byte[32 * 1024];
                try {
                    int numberOfBytes = inputStream.read(data);
                    System.out.println("Server>> " + new String(data, 0, numberOfBytes));
                } catch (IOException e) {
                    closeConnection();
                }
            }
        }).start();
    }

    private void closeConnection() {
        try {
            connection = false;
            socket.close();
            inputStream.close();
            outputStream.close();
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}   

socketIsClosed(ServerSideClient client)方法在单独的线程中工作。

public class ServerSideClient {

    private Socket socket;
    private InputStream in;
    private OutputStream out;

    private boolean connection;
    private int numOfBytes;

    public boolean isConnected() {
        return connection;
    }

    public void setConnection(boolean connection) {
        this.connection = connection;
    }

    public ServerSideClient(Socket socket) {
        this.socket = socket;
        try {
            in = socket.getInputStream();
            out = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void startListeningClient() {
        new Thread(() -> {
            listenUsers();
        }).start();
    }

    private void listenUsers() {
        while (connection == true) {
            byte[] data = new byte[32 * 1024];

            readInputFromClient(data);
            if (numOfBytes == -1) {
                try {
                    connection = false;
                    socket.close();
                    in.close();
                    out.close();
                    isConnected();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("Client disconected..");
                return;
            }
            String requestFromClient = new String(data, 0, numOfBytes);
            System.out.println("Client sended>> " + requestFromClient);


            sendResponce(requestFromClient);

        }

    }

    private void readInputFromClient(byte[] data) {
        try {
            numOfBytes = in.read(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendResponce(String resp) {
        try {
            out.write(resp.getBytes());
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

自2周以来,我一直在尝试解决此问题,Helllllllp .....

2 个答案:

答案 0 :(得分:1)

我能够复制您的问题,并且要解决的一个简单解决方案是创建一个SocketClosedListener类:

class SocketClosedListener implements Runnable {

     private final ServerSideClient client;
     private List<ServerSideClient> clients;

     public SocketClosedListener(ServerSideClient client, List<ServerSideClient> clients) {
        this.client = client;
         this.clients = clients;
     }

     @Override
     public void run() {
         while (true) {
             if (!client.isConnected()) {
                 clients.remove(client);
                 System.out.println("Client was removed " + clients.size());
                 return;
             }
             try {
                 Thread.sleep(100);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
     }
 }

在Connector类的run()方法内部,我们有这个调用:

@Override
public void run() {
    while (true) {
        try {
            System.out.println("Waiting for clients..");
            triger = true;
            socket = serverSocket.accept();
            System.out.println("Client connected");
            ServerSideClient client = createClient();
            client.setConnection(true);
            client.startListeningClient();

            clients.add(client);

            new Thread(new SocketClosedListener(client, clients)).start();//added

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

添加的行:

new Thread(new SocketClosedListener(client, clients)).start();

在单独的线程中断开连接时,负责寻找客户端。还要延迟100毫秒,以避免检查每个毫秒,这可能会在多个线程运行时引起问题。

使用此代码,我可以在控制台中找到它:

Waiting for clients..
Client sended>> hi
Client disconected..
Client was removed 1
Client disconected..
Client was removed 0

答案 1 :(得分:0)

好的,我决定使用javaRX库解决此问题。我只是使用发送到观察者服务器状态的事件。在Observable类中,我创建了:

private PublishSubject<Boolean> subject = PublishSubject.create();
    public Observable<Boolean> observable = subject.asObservable();


    public void setConnection(boolean connection) {
        this.connection = connection;
        subject.onNext(this.connection);
    }

如果客户端已连接,方法setConnection()设置为true,如果客户端初始化为断开连接,则方法设置为false。

在Observer类中,我初始化了Observable类的实例,并初始化了订阅:

client = createClient();
client.observable.subscribe(state -> removeClient(state));



public void removeClient(Boolean state) {
        System.out.println("Server state " + state);
        if (state == false) {
            clients.remove(client);
            System.out.println("Client remowed. List size: " + clients.size());
        }
    }

现在,我总是了解服务器状态,如果最后一次初始化了断开连接,则可以删除客户端。