2012-06-16 162 views
1

我正在开发基于局域网的局间消息系统。客户端从其他客户端收到消息时断开

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

  1. 服务器启动并侦听客户机上连接
  2. 客户得到所有其他连接的客户端的视图。
  3. 在连接到服务器时,我会检查数据库,如果该客户端是否授权。
  4. 如果我不检查客户端连接到服务器上的数据库,那么应用程序确实能够正常工作,如果客户端应用程序关闭,数据库中不存在客户端则更好。

相关的代码是在这里:

public void CheckUserName(string userName) 
     { 

     if (userName != "Usman") // checking in database(a static name) 
     { 
       //Check if the username is registered 
       Send("[email protected] 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); 
      } 
     } 
    } 

做任何人都可以建议怎样做才能摆脱这种坏事吗?

+0

你能否详细说明你想摆脱的“坏事”是什么?我假设它是用户登录时的数据库连接,但如果我错了,请纠正我。 – Chris

回答

0

当服务器启动并缓存这些结果时,您是否考虑过最初为所有启用的用户查询数据库?这样您可以避免必须查询每个用户连接。您可以将有权限的用户存储在字典或其他类型的查找表中。