断开连接时关闭客户端套接字

时间:2011-02-18 20:47:16

标签: c# sockets asynchronous disconnect

我有监听客户端的服务器应用程序。 让我们的客户端丢失了互联网连接并丢失了与服务器的连接。

服务器是否自动检查客户端何时断开连接?如果不是我怎么能实现这样的事情呢?

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 个答案:

答案 0 :(得分:2)

请参阅我对这个问题的回答:

TcpClient.Close doesn't close the connection

在您尝试发送数据之前,基本上没有人知道连接是否已关闭。如果失败,则关闭连接。

答案 1 :(得分:0)

根据Chris Haas的说法,我可能错了,但是我之前写过一个TCP服务器并在收到0字节时检测到关闭的连接。换句话说,在dataArrival方法中,如果bytesReceived为0,则表示连接已关闭。这似乎可以通过相当广泛的测试来实现。

答案 2 :(得分:0)

我推荐一种“民意调查”或“心跳”消息,as described here