客户端从其他客户端接收消息时断开连接

时间:2012-06-16 10:30:50

标签: c#

我正在开发基于Lan的局间邮件系统。

我的应用程序中的步骤是:

  1. 服务器启动并侦听客户端
  2. 连接上的客户端获取所有其他连接客户端的视图。
  3. 在连接到服务器时,我会在数据库中检查该客户端是否经过授权。
  4. 如果我没有在服务器的客户端连接上检查数据库,那么应用程序确实正常工作,如果客户端应用程序关闭,则数据库中不存在客户端。
  5. 相关代码在这里:

    public void CheckUserName(string userName)
            {
    
            if (userName != "Usman")  // checking in database( a static name)
            {
                  //Check if the username is registered
                  Send("sorry@Invalid Username, try another Username!!");
                  Disconnect();
                  return;
            }
            else
            {
                //If name is not duplicate then the client is connected
                this.connected =true;
                this.userName =userName;
                //Build the Usernames list and send it to the client
                StringBuilder userList = new StringBuilder();
                userList.Append(this.clientID);
                Hashtable clientTable =ClientList.GetList;
                foreach(DictionaryEntry d in clientTable)
                {
                    //Seperate the usernames by a '@'
                    userList.Append("@");
                    userList.Append(d.Value.ToString());
                }
                //Start the llistening
                lock(myClient.GetStream())
                {
                    AsyncCallback GetStreamMsgCallback = new AsyncCallback(GetStreamMsg);
                    myClient.GetStream().BeginRead(recByte,0,1024,GetStreamMsgCallback,null);
                }
                //Send the Userlist
                Send(userList.ToString());
                //Raise the Connected Event
                if(Connected!=null)
                {
                    EventArgs e = new EventArgs();
                    Connected(this, e);
                }
            }
        }
    

    有人可以建议如何摆脱这件坏事吗?

1 个答案:

答案 0 :(得分:0)

您是否考虑过在服务器启动时为所有已启用的用户查询数据库,然后缓存这些结果?这样您就可以避免查询每个用户连接。您可以将授权用户存储在字典或其他样式的查找表中。