关闭插座连接 [英] Closing sockets connection

查看:99
本文介绍了关闭插座连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个线程运行聊天程序,这样一个线程是服务器,另一个线程是客户端,一切正常,直到我单击退出按钮为止.

I have 2 threads running a chat program such that one is a server and the other is a client, everything works fine till i click the quit button.

由于单击了退出"按钮的线程的套接字被异步关闭,而另一个套接字试图读取数据,则/living线程中的读取套接字被关闭打乱,并发出错误mssg,同时被阻止适当地关闭自己的插座并安静地死掉.

since the Socket of the Thread in which the Quit button was clicked get asynchronously closed while the other socket trying to read data, the reading socket in the /living thread gets disturbed by the closure and fires an error mssg, while exepcted to properly close its own socket too and die quietly.

我需要一些建议来克服这个问题...

i need suggetions to over come this...

这是我得到的错误消息:

this is the error mssg i get:

java.net.SocketException: socket closed
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
    at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
    at sun.nio.cs.StreamDecoder.read(Unknown Source)
    at java.io.InputStreamReader.read(Unknown Source)
    at java.io.BufferedReader.fill(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at chatSockets.ChatClient.run(ChatClient.java:56)
    at java.lang.Thread.run(Unknown Source)

这就是代码:

public void run() {
    try {
        if (type==Type.CLIENT) {
            socket = new Socket(HOST, PORT);
        } else {
            ServerSocket ss = new ServerSocket(PORT);
            socket = ss.accept();
        }
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));

        while (!socket.isInputShutdown()) {
            chat.append(in.readLine()+"\n");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void actionPerformed(ActionEvent e) {
    String s = name + " : " + chat.getMssg();
    JButton src=(JButton)e.getSource();
    if (src.getText()=="Quit") {
        out.close();
        try {
            in.close();
            socket.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        System.exit(0);
    }
    else {
        out.println(s);
        chat.append(s + "\n");
        chat.clearPanel();
    }

}

推荐答案

这是预期的行为.只需处理catch块另一端的套接字关闭,然后继续执行即可.

This is expected behavior. Just handle the closing of the socket on the other end in the catch block and continue execution.

来自javadoc:

public String readLine()
                throws IOException

Read a line of text. A line is considered to be terminated by any one of a 
line feed ('\n'), a carriage return ('\r'), or a carriage return followed 
immediately by a linefeed.

Returns:
    A String containing the contents of the line, not including any 
    line-termination characters, or null if the end of the stream has been 
    reached 
Throws:
    IOException - If an I/O error occurs

因此,您在此处有两个选择:要么依赖于另一端关闭套接字并在catch块中进行清理时抛出IOException的事实,要么要使用一种干净的关闭方法,请发送一个特殊的停止令牌"传递到另一个线程,以表明您正在退出,并且应该在其末端关闭套接字.

So you have two options here: either rely on the fact that an IOException is thrown when the other end closes the socket and do cleanup in the catch block or if you want a clean way of shutting down send a special "stop token" to the other thread signaling it that you are exiting and that it should close the socket on its end.

这篇关于关闭插座连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆