客户端断开JAVA后socket没有关闭

时间:2018-02-02 06:54:36

标签: java sockets tcp serversocket

嗨我有一个代码,我想在客户端断开聊天时关闭套接字。但是每当客户端类型结束时,套接字仍处于活动状态。  我怎么会这样做?我尝试了几个教程,但对我没用。

这是我的代码:

public void server(){
        Thread serverThread = new Thread(new Runnable() {
            @Override
            public void run() {

                try {

                    serverSocket = new ServerSocket(port);

                    while (true){

                        try {
                            System.out.println("Waiting for connection...");

                            socket = serverSocket.accept();

                            System.out.println("New connection established!");
                            System.out.println(username+" is connected");

                            din = new DataInputStream(socket.getInputStream());
                            dout = new DataOutputStream(socket.getOutputStream());

                            do {
                                cut = true;
                                read = din.readUTF();

                                if (getForDisplay()!=null){
                                    setForDisplay(getForDisplay()+"\n"+read);
                                }else {
                                    setForDisplay(read);
                                }
                            }
                            while (!read.equals("end"));

                            System.out.println("closed!"); // not working too
                        }catch (IOException e){
                            e.printStackTrace();
                        }finally {
                            cut = false;
                            try {
                                cut = false;
                                System.out.println("closed! finally");
                                din.close();
                                dout.close();
                                socket.close();
                            }catch (IOException e){
                                e.printStackTrace();
                            }
                        }
                    }

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

            }
        });
        serverThread.start();
    }

1 个答案:

答案 0 :(得分:0)

放一个

  break;

在关闭while(true)循环的大括号之前。