我尝试编写一个简单的聊天软件 . 但我是新的套接字编程,因此我有一个问题:
当聊天客户端向服务器发送“goodby”时,服务器应关闭客户端的连接并释放所有资源 . 但在关闭套接字后,“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;
}
}
2 回答
根据Java Docs
是 . 但是,通常情况下,您将关闭已包裹在套接字输出流中的最外层
OutputStream
或Writer
. 这将刷新它,关闭流,关闭输入流,并关闭套接字 .