当接收端没有客户端时,服务器套接字线程被挂起

时间:2018-06-06 07:33:11

标签: c# .net sockets serversocket

我是用户ServerSocketLib,用于Windows服务和Windows窗口之间的通信,当接收器客户端可用时,它可正常工作,它接收消息并将消息发送回服务器。但有些客户端如何被杀死然后当服务器尝试向客户端发送消息时线程被挂起。我们如何打破被绞死的线程。这是我用于向客户端发送消息的以下代码。

/// <summary>
/// This method is used to send the message from server to client.
/// </summary>
/// <param name="message"></param>
public void SendMessageToClient(string message, string clientGuid, int sessionId)
{
    AbstractTcpSocketClientHandler clienthandler = null;
    try
    {
        ClientInfo[] clientList = this.server.GetClientList();
        if (clientList.Length == 0)
        {
            log.WarnFormat("Socket: No clients are connected.");
            return;
        }
        for (int i = 0; i < clientList.Length; i++)
        {
            clienthandler = clientList[i].TcpSocketClientHandler;
            if (clientList[i].TcpSocketClientHandler.ToString() == clientGuid)
            {
                byte[] buffer = System.Text.ASCIIEncoding.Unicode.GetBytes(message);
                BasicMessage basicmessage = new BasicMessage(this.serverGuid, buffer);
                clienthandler.SendAsync(basicmessage);
                log.DebugFormat("Socket: sending message to client clientuid: {0}", clientGuid);
            }
        }
    }
    catch (Exception ex)
    {
        log.ErrorFormat("Exception occurred while sending message {0}, {1}", ex.Message, ex.StackTrace);
        if (clienthandler != null)
        {
            clienthandler.Close();
            CreateNewSocketConnection(sessionId);
        }
    }
}

0 个答案:

没有答案