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

C# 从其他客户端接收消息时客户端断开连接,c#,C#,我正在开发基于局域网的办公室间消息传递系统 我的应用程序中的步骤包括: 服务器启动并侦听客户端 连接上的客户端获取所有其他连接客户端的视图 在连接到服务器时,我会在数据库中检查该客户机是否经过授权 如果我不签入与服务器的客户端连接上的数据库,则应用程序会正常工作。如果数据库中不存在客户端,则客户端应用程序会关闭 相关代码如下: public void CheckUserName(string userName) { if (userName != "Usman"

我正在开发基于局域网的办公室间消息传递系统

我的应用程序中的步骤包括:

  • 服务器启动并侦听客户端
  • 连接上的客户端获取所有其他连接客户端的视图
  • 在连接到服务器时,我会在数据库中检查该客户机是否经过授权
  • 如果我不签入与服务器的客户端连接上的数据库,则应用程序会正常工作。如果数据库中不存在客户端,则客户端应用程序会关闭
  • 相关代码如下:

    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);
                }
            }
        }
    

    是否有人可以建议如何消除这种不好的情况?

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

    您能详细说明一下您想要摆脱的“坏东西”是什么吗?我假设这是用户登录时的数据库连接,但如果我错了,请纠正我。