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

减小字体 增大字体

System.EventHandler(this.btnConnect_Click);
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(464, 309);
   this.Controls.Add(this.btnConnect);
   this.Controls.Add(this.clientName);
   this.Controls.Add(this.btnDisconnect);
   this.Controls.Add(this.statusBar1);
   this.Controls.Add(this.btnSend);
   this.Controls.Add(this.ChatOut);
   this.Controls.Add(this.checkBox1);
   this.Controls.Add(this.rtbChatIn);
   this.Controls.Add(this.lbChatters);
   this.Name = "Form1";
   this.Text = "Form1";
   this.ResumeLayout(false);

  }
  #endregion

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

  private void EstablishConnection()
  {
   statusBar1.Text = "正在连接到服务器";
   
   try
   {
    clientsocket = new TcpClient(serveraddress,serverport);
    ns = clientsocket.GetStream();
    sr = new StreamReader(ns);
    connected = true;
   
   }
   catch (Exception)
   {
    MessageBox.Show("不能连接到服务器!","错误",
     MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    statusBar1.Text = "已断开连接";
   }
  }

  private void RegisterWithServer()
  {
   lbChatters.Items.Clear();

   clientname = clientName.Text;
   try
   {
    string command = "CONN|" + clientname; //+"\r\n";
    Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
    ns.Write(outbytes,0,outbytes.Length);


    string serverresponse = sr.ReadLine();
    serverresponse.Trim();
    string[] tokens = serverresponse.Split('|');
    if(tokens[0] == "LIST")
    {
     statusBar1.Text = "已连接";
     btnDisconnect.Enabled = true;
    }
    if(tokens[1] != "")
    {
     for(int n=1; n<tokens.Length;n++)
      lbChatters.Items.Add(tokens[n].Trim(new char[]{'\r','\n'}));
    }
    this.Text = clientname + ":已连接到服务器";    

   }
   catch (Exception ex)
   {
    MessageBox.Show("注册时发生错误!"+ex.Message,"错误",
     MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    connected = false;
   }
  }

  private void ReceiveChat()
  {
   bool keepalive = true;
   while (keepalive)
   {
    try
    {
     Byte[] buffer = new Byte[1024];  // 2048???
     ns.Read(buffer,0,buffer.Length);
     string chatter = System.Text.Encoding.ASCII.GetString(buffer);
     string[] tokens = chatter.Split(new Char[]{'|'});

     if (tokens[0] == "CHAT")
     {
      rtbChatIn.AppendText(tokens[1]);
//      if(logging)
//       logwriter.WriteLine(tokens[1]);
     }
     if (tokens[0] == "PRIV")
     {
      rtbChatIn.AppendText("Private from ");
      rtbChatIn.AppendText(tokens[1].Trim() );
      rtbChatIn.AppendText(tokens[2] + "\r\n");
//      if(logging)
//      {
//       logwriter.Write("Private from ");
//       logwriter.Write(tokens[1].Trim() );
//       logwriter.WriteLine(tokens[2] + "\r\n");
//      }
     }
     if (tokens[0] == "JOIN")
     {
      rtbChatIn.AppendText(tokens[1].Trim() );
      rtbChatIn.AppendText(" has joined the Chat\r\n");
//      if(logging)
//      {
//       logwriter.WriteLine(tokens[1]+" has joined the Chat");
//      }
      string newguy = tokens[1].Trim(new char[]{'\r','\n'});
      lbChatters.Items.Add(newguy);
     }
     if (tokens[0] == "GONE")
     {
      rtbChatIn.AppendText(tokens[1].Trim() );
      rtbChatIn.AppendText(" has left the Chat\r\n");
//      if(logging)
//      {
//       logwriter.WriteLine(tokens[1]+" has left the Chat");
//      }
      lbChatters.Items.Remove(tokens[1].Trim(new char[]{'\r','\n'}));
     }
     if (tokens[0] == "QUIT")
     {
      ns.Close();
      clientsocket.Close();
      keepalive = false;
      statusBar1.Text = "服务器端已停止";
      connected= false;
      btnSend.Enabled = false;
      btnDisconnect.Enabled = false;
     }
    }
    catch(Exception){}
   }
  }

  private void QuitChat()
  {
   if(connected)
   {
    try
    {
     string command = "GONE|" + clientname;
     Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
     ns.Write(outbytes,0,outbytes.Length);
     clientsocket.Close();
    }
    catch(Exception ex)
    {
     MessageBox.Show(ex.Message);
    }
   }
//   if(logging)
//    logwriter.Close();
   if(receive != null && receive.IsAlive)
    receive.Abort();
   this.Text = "客户端";
   
   connected = false;

  }

  private void btnSend_Click(object sender, System.EventArgs e)
  {
   if(connected)
   {
    try
    {
     string command = "CHAT|" + clientname+": "+ChatOut.Text+"\r\n";
     Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
     ns.Write(outbytes,0,outbytes.Length);
     //clientsocket.Close();
    }
    catch(Exception ex)
    {
     MessageBox.Show(ex.Message);
    }
   }
  }

  private void btnConnect_Click(object sender, System.EventArgs e)
  {
   EstablishConnection();
   RegisterWithServer();
   if(connected)
   {   
    receive = new Thread(new ThreadStart(ReceiveChat));
    receive.Start();
   }
  }

  private void btnDisconnect_Click(object sender, System.EventArgs e)
  {
   QuitChat();
  }
 }
}



上一页  [1] [2] [3] 

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

用户名: 查看更多评论

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

内 容:

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