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

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

 
     程序的主体部分应是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[n];
  
  
  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[n];
  
  
  SendToClient(cl, clientcommand);
  
  
  }
  
  
  }
  
  
  if (tokens[0] == "PRIV")
  
  
  {
  
  
  string destclient = tokens[3];
  
  
  for(int n=0; n
  
  
  {
  
  
  Client cl = (Client)clients[n];
  
  
  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[n];
  
  
  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文件)程序运行图

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值