我有监听客户端的服务器应用程序 . 让客户失去互联网连接并失去与服务器的连接 .
服务器是否自动检查客户端何时断开连接?如果不是我怎么可以实现这样的事情?
Main.cs http://pastebin.com/fHYpErz7
ServerSocket.cs:http://pastebin.com/erw4tzdp
Client.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace jM2
{
class Client
{
private int clientConnectionID;
private Socket clientSocket;
private string clientIP;
private byte[] clientBuffer = new byte[1024];
public Client(int connectionID, Socket connectionSocket)
{
clientConnectionID = connectionID;
clientSocket = connectionSocket;
clientIP = connectionSocket.RemoteEndPoint.ToString();
clientSocket.BeginReceive(clientBuffer, 0, clientBuffer.Length, SocketFlags.None, new AsyncCallback(dataArrival), null);
}
public void Disconnect()
{
clientSocket.Close();
}
private void dataArrival(IAsyncResult iar)
{
int bytesReceived = clientSocket.EndReceive(iar);
clientSocket.BeginReceive(clientBuffer, 0, clientBuffer.Length, SocketFlags.None, new AsyncCallback(dataArrival), null);
}
}
}
3 回答
看看我对这个问题的回答:
TcpClient.Close doesn't close the connection
基本上没有人知道在您尝试发送数据之前连接是否已关闭 . 如果失败,则关闭连接 .
根据Chris Haas的说法,我可能错了,但是我之前写过一个TCP服务器并在收到0字节时检测到关闭的连接 . 换句话说,在dataArrival方法中,如果bytesReceived为0,则表示连接已关闭 . 这似乎通过相当广泛的测试工作 .
我推荐一种"poll"或"heartbeat"消息,as described here .