程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 簡單的多人聊天(C#_Socket)

簡單的多人聊天(C#_Socket)

編輯:關於C語言

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 );
  
  }

  Windows 窗體設計器生成的代碼#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() +" ";
     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.Start(); 
  }
 }
}

/**//***************************** clIEnt類 ********************/

/**//************************** 放於 chatServer 項目中 *********/

using System;
using System.Threading;

namespace Chat_Server
{
 using System.Net.Sockets;
 using System.Net;

 /**////
 /// ClIEnt 的摘要說明。
 ///
 public class ClIEnt
 {
  private Thread clthread;
  private EndPoint endpoint;
  private string name;
  private Socket sock;

  public ClIEnt(string _name, EndPoint _endpoint, Thread _thread, Socket _sock)
  {
   // TODO: 在此處添加構造函數邏輯
   clthread = _thread;
   endpoint = _endpoint;
   name = _name;
   sock = _sock;
  }

  public override string ToString()
  {
   return endpoint.ToString()+ " : " + name;
  }

  public Thread CLThread
  {
   get{return clthread;}
   set{clthread = value;}
  }

  public EndPoint Host
  {
   get{return endpoint;}
   set{endpoint = value;}
  }

  public string Name
  {
   get{return name;}
   set{name = value;}
  }

  public Socket Sock
  {
   get{return sock;}
   set{sock = value;}
  }
 }
}

/**//***************************** chatClIEnt ************************************/

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

using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Chat_ClIEnt
{
 /**//// <summary>
 /// Form1 的摘要說明。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.CheckBox checkBox1;
  private System.Windows.Forms.StatusBar statusBar1;

  NetworkStream ns;
  StreamReader sr;
  TcpClient clIEntsocket;
  bool connected;
  Thread receive;
  string serveraddress = "219.228.231.85";
  int serverport = 6666;

  private System.Windows.Forms.RichTextBox rtbChatIn;
  private System.Windows.Forms.ListBox lbChatters;
  private System.Windows.Forms.TextBox ChatOut;
  private System.Windows.Forms.Button btnDisconnect;
  private System.Windows.Forms.Button btnSend;
  private System.Windows.Forms.TextBox clIEntName;

  string clIEntname;
  private System.Windows.Forms.Button btnConnect;

  private System.ComponentModel.Container components = null;

  public Form1()
  {
  
   InitializeComponent();

  }

  /**//// <summary>
  /// 清理所有正在使用的資源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if(receive != null)
    {
     QuitChat();
    }
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  Windows 窗體設計器生成的代碼#region Windows 窗體設計器生成的代碼
  /**//// <summary>
  /// 設計器支持所需的方法 - 不要使用代碼編輯器修改
  /// 此方法的內容。
  /// </summary>
  private void InitializeComponent()
  {
   this.lbChatters = new System.Windows.Forms.ListBox();
   this.rtbChatIn = new System.Windows.Forms.RichTextBox();
   this.checkBox1 = new System.Windows.Forms.CheckBox();
   this.ChatOut = new System.Windows.Forms.TextBox();
   this.btnSend = new System.Windows.Forms.Button();
   this.statusBar1 = new System.Windows.Forms.StatusBar();
   this.btnDisconnect = new System.Windows.Forms.Button();
   this.clIEntName = new System.Windows.Forms.TextBox();
   this.btnConnect = new System.Windows.Forms.Button();
   this.SuspendLayout();
   //
   // lbChatters
   //
   this.lbChatters.ItemHeight = 12;
   this.lbChatters.Location = new System.Drawing.Point(32, 40);
   this.lbChatters.Name = "lbChatters";
   this.lbChatters.Size = new System.Drawing.Size(112, 172);
   this.lbChatters.TabIndex = 0;
   //
   // rtbChatIn
   //
   this.rtbChatIn.Location = new System.Drawing.Point(160, 40);
   this.rtbChatIn.Name = "rtbChatIn";
   this.rtbChatIn.Size = new System.Drawing.Size(208, 176);
   this.rtbChatIn.TabIndex = 2;
   this.rtbChatIn.Text = "";
   //
   // checkBox1
   //
   this.checkBox1.Location = new System.Drawing.Point(16, 248);
   this.checkBox1.Name = "checkBox1";
   this.checkBox1.TabIndex = 3;
   this.checkBox1.Text = "checkBox1";
   //
   // ChatOut
   //
   this.ChatOut.Location = new System.Drawing.Point(136, 248);
   this.ChatOut.Name = "ChatOut";
   this.ChatOut.Size = new System.Drawing.Size(136, 21);
   this.ChatOut.TabIndex = 4;
   this.ChatOut.Text = "message";
   //
   // btnSend
   //
   this.btnSend.Location = new System.Drawing.Point(336, 248);
   this.btnSend.Name = "btnSend";
   this.btnSend.TabIndex = 5;
   this.btnSend.Text = "send";
   this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
   //
   // statusBar1
   //
   this.statusBar1.Location = new System.Drawing.Point(0, 287);
   this.statusBar1.Name = "statusBar1";
   this.statusBar1.Size = new System.Drawing.Size(464, 22);
   this.statusBar1.TabIndex = 6;
   this.statusBar1.Text = "statusBar1";
   //
   // btnDisconnect
   //
   this.btnDisconnect.Enabled = false;
   this.btnDisconnect.Location = new System.Drawing.Point(392, 112);
   this.btnDisconnect.Name = "btnDisconnect";
   this.btnDisconnect.Size = new System.Drawing.Size(64, 32);
   this.btnDisconnect.TabIndex = 7;
   this.btnDisconnect.Text = "斷開";
   this.btnDisconnect.Click += new System.EventHandler(this.btnDisconnect_Click);
   //
   // clIEntName
   //
   this.clIEntName.Location = new System.Drawing.Point(96, 8);
   this.clientName.Name = "clIEntName";
   this.clIEntName.TabIndex = 8;
   this.clIEntName.Text = "name";
   //
   // btnConnect
   //
   this.btnConnect.Location = new System.Drawing.Point(392, 56);
   this.btnConnect.Name = "btnConnect";
   this.btnConnect.Size = new System.Drawing.Size(64, 32);
   this.btnConnect.TabIndex = 9;
   this.btnConnect.Text = "連接";
   this.btnConnect.Click += new 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; //+" ";
    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[]{' ',' '}));
    }
    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] + " ");
//      if(logging)
//      {
//       logwriter.Write("Private from ");
//       logwriter.Write(tokens[1].Trim() );
//       logwriter.WriteLine(tokens[2] + " ");
//      }
     }
     if (tokens[0] == "JOIN")
     {
      rtbChatIn.AppendText(tokens[1].Trim() );
      rtbChatIn.AppendText(" has joined the Chat ");
//      if(logging)
//      {
//       logwriter.WriteLine(tokens[1]+" has joined the Chat");
//      }
      string newguy = tokens[1].Trim(new char[]{' ',' '});
      lbChatters.Items.Add(newguy);
     }
     if (tokens[0] == "GONE")
     {
      rtbChatIn.AppendText(tokens[1].Trim() );
      rtbChatIn.AppendText(" has left the Chat ");
//      if(logging)
//      {
//       logwriter.WriteLine(tokens[1]+" has left the Chat");
//      }
      lbChatters.Items.Remove(tokens[1].Trim(new char[]{' ',' '}));
     }
     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+" ";
     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. 下一頁:
Copyright © 程式師世界 All Rights Reserved