服务器套接字关闭 SendCallback 中的连接

Server socket close the connection in SendCallback

我创建了一个 windows form 服务器套接字和 android app 客户端套接字。对于服务器套接字,我遵循 this tutorial from MSDN。我的问题是当我从服务器调用发送时,套接字将关闭并且我无法再收到来自用户的消息。当我从 SendCallback 方法中删除 ShotDownClose 套接字时,在我停止服务器之前没有任何内容发送到客户端并且消息将发送到客户端。这是 SendCallback 方法:

private  void SendCallback(IAsyncResult ar)
{
    Socket handler = (Socket)ar.AsyncState;
    int bytesSent = handler.EndSend(ar);

    // When I delete this two lines, nothing send to client
    handler.Shutdown(SocketShutdown.Both);
    handler.Close();
}

我不明白为什么这些行必须在 SendCallback

如 msdn (here) 的备注部分所述。关闭处理程序会强制进行刷新并发送套接字中剩余的任何内容。

When using a connection-oriented Socket, always call the Shutdown method before closing the Socket. This ensures that all data is sent and received on the connected socket before it is closed.

msdn文章上实现的设计,需要close。 google 搜索将向您展示不同的实现方式。

希望对您有所帮助。

回答我的问题: 服务器套接字将数据放入缓冲区(WireShark 是这么说的)但是android 客户端无法读取数据。我发现这是因为我在 java 客户端中使用 in.readLine() 从套接字读取数据,但它仅在发送数据末尾有结束行时有效,所以我只添加 \n 在来自服务器的任何消息的末尾,现在一切正常。