【发布时间】:2015-04-10 11:20:42
【问题描述】:
我尝试写一个简单的聊天软件。 但我是新的套接字编程,因此我有一个问题:
当聊天客户端向服务器发送“再见”时,服务器应该关闭客户端的连接并释放所有资源。 但是在我关闭套接字后,“isConnected()”标志仍然显示“true”。
我发现了一些类似问题的帖子,但我必须承认我没有理解那里的所有解释。
但是 socket.isConnected() 似乎没有显示套接字的当前连接状态?
是这样吗?
那么服务器如何关闭客户端连接(套接字)并将所有资源等释放回操作系统?
我想避免随着时间的推移服务器将保持“死”连接\套接字。
只执行“socket.close”就够了吗?
我的服务器代码:
class connection extends Thread
{
public Socket client;
public PrintStream output;
private BufferedReader input;
...
...
while(true) //loop where server waits for client's message
{
//****** wait for client's message
line=input.readLine();
//******* Client wants to leave chat - so close its connection , release server ressources, close this thread...
if (line.equals("goodbye"))
{
//close I/O streams
this.input.close();
this.output.flush();
this.output.close();
//Close Socket
client.close(); //<-- results in: .isClosed()==true but : .isConnected()==true
//close thread (not clear if neccessary)
this.stop();
//exit loop / this should also exit and thus close this thread
break;
}
}
【问题讨论】:
-
提示:在 Java 中,类名以大写字母开头。叫它
Connection。 -
@Tichodroma 严格来说,他们不必这样做。
-
当你再见时我会跳出 while 循环,然后关闭那里的套接字。正如 EJP 下面所说,您只需要关闭 IO 流,它就会关闭套接字。还将关闭放入 finally {} 子句中,以免错过。