您的位置:首页 > 编程语言 > C#

浅析C#中的套接字编程(3)

2005-01-05 23:45 309 查看
浅析C#中的套接字编程(3)
作者: 王凯明   www.ASPCool.com 时间:2002-4-10 21:19:37  
     程序的主体部分应是ServiceClient()函数。该函数是一个独立的线程,其主要部分是一个while循环。在循环体内,程序处理各种客户端命令。服务器端接收来自客户端的以ASCII码给出的字符串,其中包含了一个“|”形式的分隔符。字符串中“|”以前的部分就是具体的命令,包括CONN、CHAT、PRIV、GONE四种类型。CONN命令建立一个新的客户端连接,将现有的用户列表发送给新用户并告知其他用户有一个新用户加入。CHAT命令将新的信息发送给所有用户。PRIV命令将悄悄话发送给某个用户。GONE命令从用户列表中除去一个已离开的用户并告知其他的用户某某已经离开了。同时,GONE命令可以设置布尔型的变量keepalive为false从而结束与客户端连接的线程。ServiceClient()函数如下:
  
  
  private void ServiceClient()
  
  
  {
  
  
  Socket client = clientsocket;
  
  
  bool keepalive = true;
  
  
  
  
  while (keepalive)
  
  
  {
  
  
  Byte[] buffer = new Byte[1024];
  
  
  client.Receive(buffer);
  
  
  string clientcommand = System.Text.Encoding.ASCII.GetString(buffer);
  
  
  
  
  string[] tokens = clientcommand.Split(new Char[]{'|'});
  
  
  Console.WriteLine(clientcommand);
  
  
  
  
  if (tokens[0] == "CONN")
  
  
  {
  
  
  for(int n=0; n
  
  
  {
  
  
  Client cl = (Client)clients
;
  
  
  SendToClient(cl, "JOIN|" + tokens[1]);
  
  
  }
  
  
  EndPoint ep = client.RemoteEndPoint;
  
  
  Client c = new Client(tokens[1], ep, clientservice, client);
  
  
  clients.Add(c);
  
  
  string message = "LIST|" + GetChatterList() +"/r/n";
  
  
  SendToClient(c, message);
  
  
  
  
  lbClients.Items.Add(c);
  
  
  
  
  }
  
  
  if (tokens[0] == "CHAT")
  
  
  {
  
  
  for(int n=0; n
  
  
  {
  
  
  Client cl = (Client)clients
;
  
  
  SendToClient(cl, clientcommand);
  
  
  }
  
  
  }
  
  
  if (tokens[0] == "PRIV")
  
  
  {
  
  
  string destclient = tokens[3];
  
  
  for(int n=0; n
  
  
  {
  
  
  Client cl = (Client)clients
;
  
  
  if(cl.Name.CompareTo(tokens[3]) == 0)
  
  
  SendToClient(cl, clientcommand);
  
  
  if(cl.Name.CompareTo(tokens[1]) == 0)
  
  
  SendToClient(cl, clientcommand);
  
  
  }
  
  
  }
  
  
  if (tokens[0] == "GONE")
  
  
  {
  
  
  int remove = 0;
  
  
  bool found = false;
  
  
  int c = clients.Count;
  
  
  for(int n=0; n
  
  
  {
  
  
  Client cl = (Client)clients
;
  
  
  SendToClient(cl, clientcommand);
  
  
  if(cl.Name.CompareTo(tokens[1]) == 0)
  
  
  {
  
  
  remove = n;
  
  
  found = true;
  
  
  lbClients.Items.Remove(cl);
  
  
  }
  
  
  }
  
  
  if(found)
  
  
  clients.RemoveAt(remove);
  
  
  client.Close();
  
  
  keepalive = false;
  
  
  }
  
  
  }
  
  
  }
  
  
  这样,服务器端程序就基本完成了。(其他略次要的代码可以参见源代码中的Form1.cs文件)程序运行图示如下:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息