我尝试编写一个简单的聊天软件。 但我是新的套接字编程,因此我有一个问题:
当聊天客户端发送" goodby"服务器应关闭客户端的连接并释放所有资源。 但在我关闭套接字后," isConnected()"国旗仍显示" true"。
我找到了一些有类似问题的帖子,但我必须承认我并不了解那里的所有解释。
但似乎socket.isConnected()没有显示套接字的当前连接状态?
这是对的吗?
那么服务器如何关闭客户端连接(套接字)并将所有资源等释放回操作系统?
我想避免随着时间的推移服务器将保持“死亡”#34;连接\套接字。
只需执行" 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;
}
}
答案 0 :(得分:2)
public boolean isConnected()
返回的连接状态 插座。
注意:关闭套接字不会清除其连接状态, 这意味着这个方法对于一个封闭的套接字将返回true(参见 isClosed())如果在关闭之前已成功连接。
答案 1 :(得分:1)
只需执行&#34; socket.close&#34; ?
是。但是,通常情况下,您将关闭套接字输出流周围的最外层OutputStream
或Writer
。这将刷新它,关闭流,关闭输入流,然后关闭套接字。