检测插座中的断开连接

时间:2016-04-19 17:18:40

标签: java sockets

我正在创建一个“echo”服务器,收到消息后只需将其发回。我设法使多客户端工作,但我想进行某种断开检测。我尝试通过从服务器发送单个字符,然后使用客户端中的另一个字符进行回复来使其工作。但是,我无法让它发挥作用。

您如何建议我进行断线检测?

MessageServer.java

import java.net.*;
import java.io.*;

public class MessageServer {
    static int clientCount = 0;
    public static void main(String[] args) throws IOException {
        try(ServerSocket servSocket = new ServerSocket(16384)){
            while(true){
                Socket socket = servSocket.accept();
                addClient();
                new ServerThread(socket, clientCount).start();

            }

        } catch(IOException e) {
            System.out.println("Exception caught when trying to listen on port 16384 or listening for a connection");
            System.out.println(e.getMessage());
        }

    }

    public static void addClient(){
        clientCount++;
    }
}

ServerThread.java

import java.net.*;
import java.io.*;

public class ServerThread extends Thread {
    private Socket cltSocket;
    private BufferedReader in;
    private PrintWriter out;
    private int num;
    public ServerThread(Socket clientSocket, int count) {
        cltSocket = clientSocket;
        num = count;
    }
    public void run() {
        String input;

        try {
            out = new PrintWriter(cltSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(cltSocket.getInputStream()));
            System.out.println("Client " + num + " connected!");

            while(cltSocket.isConnected() && !cltSocket.isClosed()){
                if(in.ready()){
                    input = in.readLine();
                    if(input != null && !(input.equalsIgnoreCase("exit"))){
                        System.out.print("New input: ");
                        System.out.println(input);
                        out.println(input);
                        out.flush();
                    } else if(input.equalsIgnoreCase("exit")){
                        disconnect();
                    }
                }
            }
        } catch(SocketException e) {
            disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

    public void disconnect(){
        System.out.println("Client " + num + " disconnected!");
        out.close();
        try {
            in.close();
            cltSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

MessageClient.java

import java.net.*;
import java.io.*;

public class MessageClient {

    public static void main(String[] args) {

        if(args.length != 2) {
            System.out.println("Invalid parameters! Format as: (hostname) (port)");
            System.exit(1);
        }

        String hostname = args[0];
        int port = Integer.parseInt(args[1]);

        try {
            Socket socket = new Socket(hostname, port);
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Connected!");

            while(socket.isConnected() && !socket.isClosed()){
                String output;
                if(con.ready()) {
                    output = con.readLine();
                    out.println(output);
                    if(output.equalsIgnoreCase("exit")) {
                        socket.close();
                    }
                }

                if(in.ready()){
                    String li = in.readLine();
                    if(li != null) {
                        System.out.println(li);
                    }
                }
            }


            System.out.println("Disconnected!");
            con.close();
            out.close();
            in.close();
            System.exit(0);
        } catch(SocketException e) {
            System.err.println("Socket error:" + e);
        } catch(UnknownHostException e) {
            System.err.println("Invalid host");
        } catch(IOException e) {
            System.err.println("IO Error: " + e);
        } 

    }

}

1 个答案:

答案 0 :(得分:1)

有办法做到这一点:

如果您通过调用BufferedReader.getLine()读取 BufferedReader 而另一侧套接字消失了,那么您将获得 SocketException ...这是一种方法检查丢失的连接