您当前的位置:中客资源站网络学院.NET专区综合应用 → 文章内容 退出登录 用户管理
本类热门文章
相关下载
简单的多人聊天(C#.Socket).
作者:中客资源  来源:中客资源  发布时间:2007-2-7 2:55:01

减小字体 增大字体

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace Chat_Server
{
 /// <summary>
 /// Form1 的摘要说明。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  static int listenport=6666;
  Socket clientsocket;
  private System.Windows.Forms.ListBox lbClients;
  ArrayList clients;
  private System.Windows.Forms.Button button1;
  Thread clientservice;
  private System.Windows.Forms.Label label1;
  Thread threadListen;

  public Form1()
  {
   
   InitializeComponent();

  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    
    if(clientservice != null)
    {
     clientservice.Abort();
    }
    if(threadListen != null)
    {
     try
     {
      threadListen.Abort();
     }
     catch(Exception ex)
     {
      threadListen = null;
     }
    }    

    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
   
  }

  #region Windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.lbClients = new System.Windows.Forms.ListBox();
   this.button1 = new System.Windows.Forms.Button();
   this.label1 = new System.Windows.Forms.Label();
   this.SuspendLayout();
   //
   // lbClients
   //
   this.lbClients.ItemHeight = 12;
   this.lbClients.Location = new System.Drawing.Point(16, 24);
   this.lbClients.Name = "lbClients";
   this.lbClients.Size = new System.Drawing.Size(184, 268);
   this.lbClients.TabIndex = 0;
   //
   // button1
   //
   this.button1.Location = new System.Drawing.Point(272, 56);
   this.button1.Name = "button1";
   this.button1.TabIndex = 1;
   this.button1.Text = "button1";
   this.button1.Click += new System.EventHandler(this.button1_Click);
   //
   // label1
   //
   this.label1.Location = new System.Drawing.Point(240, 136);
   this.label1.Name = "label1";
   this.label1.Size = new System.Drawing.Size(120, 32);
   this.label1.TabIndex = 2;
   this.label1.Text = "label1";
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(368, 309);
   this.Controls.Add(this.label1);
   this.Controls.Add(this.button1);
   this.Controls.Add(this.lbClients);
   this.Name = "Form1";
   this.Text = "Form1";
   this.Load += new System.EventHandler(this.Form1_Load);
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  private void StartListening()
  {
    TcpListener listener = new TcpListener(listenport);
    listener.Start();
   label1.Text = "listening....";
   while (true)
   {
    try
    {
    
     Socket s = listener.AcceptSocket();
     clientsocket = s;
     clientservice = new Thread(new ThreadStart(ServiceClient));
     clientservice.Start();
    }
    catch(Exception ex)
    {
     MessageBox.Show("listening Error: "+ex.Message);
    }
   }   
  }
  private void ServiceClient()
  {
   Socket client = clientsocket;
   bool keepalive = true;


   while (keepalive)
   {
    Byte[] buffer = new Byte[1024];
    int bufLen = 0;
    try
    {
     bufLen = client.Available ;
     
     client.Receive(buffer,0,bufLen,SocketFlags.None);
     if(bufLen==0)
      continue;    
    }
    catch(Exception ex)
    {
     MessageBox.Show("Receive Error:"+ex.Message);
     return;
    }
    
    string clientcommand = System.Text.Encoding.ASCII.GetString(buffer).Substring(0,bufLen);

    string[] tokens = clientcommand.Split(new Char[]{'|'});
    Console.WriteLine(clientcommand);

    if (tokens[0] == "CONN")
    {
     for(int n=0; n<clients.Count;n++)
     {
      Client cl = (Client)clients[n];
      SendToClient(cl, "JOIN|" + tokens[1]);
     }
     EndPoint ep = client.RemoteEndPoint;
     Client c = new Client(tokens[1], ep, clientservice, client);
     
     string message = "LIST|" + GetChatterList() +"\r\n";
     SendToClient(c, message);

     clients.Add(c);


     lbClients.Items.Add(c);


    }
    if (tokens[0] == "CHAT")
    {
     for(int n=0; n<clients.Count;n++)
     {
      Client cl = (Client)clients[n];
      SendToClient(cl, clientcommand);
     }
    }
    if (tokens[0] == "PRIV")
    {
     string destclient = tokens[3];
     for(int n=0; n<clients.Count;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<clients.Count;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;
    }
   }
  }

  private string GetChatterList()
  {
   string result = "";

   for(int i=0;i<clients.Count;i++)
   {
    result += ((Client)clients[i]).Name+"|";
   }
   return result;

  }

  private void SendToClient(Client cl,string clientCommand)
  {
   Byte[] message = System.Text.Encoding.ASCII.GetBytes(clientCommand);
   Socket s = cl.Sock;
   if(s.Connected)
   {
    s.Send(message,message.Length,0);
   }
  }

  private void Form1_Load(object sender, System.EventArgs e)
  {
   clients = new ArrayList();
  }

  private void button1_Click(object sender, System.EventArgs e)
  {
   threadListen = new Thread(new ThreadStart(StartListening));
   threadListen

[1] [2] [3]  下一页

[] [返回上一页] [打 印]
文章评论 (评论内容只代表网友观点,与本站立场无关!)

用户名: 查看更多评论

分 值:100分 85分 70分 55分 40分 25分 10分 0分

内 容:

         (注“”为必填内容。) 验证码: 验证码,看不清楚?请点击刷新验证码