程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> c#完成多線程局域網聊天體系

c#完成多線程局域網聊天體系

編輯:C#入門知識

c#完成多線程局域網聊天體系。本站提示廣大學習愛好者:(c#完成多線程局域網聊天體系)文章只能為提供參考,不一定能成為您想要的結果。以下是c#完成多線程局域網聊天體系正文


認為好有點贊助就頂一下啦。

socke編程,支撐多客戶端,多線程操作防止界面卡逝世。

開啟socket

private void button1_Click(object sender, EventArgs e)
   {
     try
     {
       int port = int.Parse(txt_port.Text);
       string host = txt_ip.Text;
       //創立終結點
       IPAddress ip = IPAddress.Parse(host);
       IPEndPoint ipe = new IPEndPoint(ip, port);
       //創立Socket並開端監聽
       newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //創立一個Socket對象,假如用UDP協定,則要用SocketTyype.Dgram類型的套接字
       newsock.Bind(ipe);  //綁定EndPoint對象
       newsock.Listen(0);  //開端監聽
       //為新樹立的銜接創立新的Socket
       acceptClientThread = new Thread(new ThreadStart(AcceptClient));
       acceptClientThread.Start();
       SetText("開端監聽");
     }
     catch (Exception exp)
     {
       CommonFunction.WriteLog(exp, exp.Message);
     }
   }

監控端口,吸收客戶端

/// <summary>
    /// 接收客戶端,可接收多個客戶端同時連入,並對連入的客戶端注冊到客戶端列表
    /// </summary>
    public void AcceptClient()
    {
      try
      {
        while (true)
        {
          Socket client = newsock.Accept();
          ip = client.Handle;
          RegeistUser(client.Handle, client);
          Thread clientThread = new Thread(new ParameterizedThreadStart(ReceiveData));
          object o = client;
          clientThread.Start(o);
        }
      }
      catch (Exception exp)
      {
        CommonFunction.WriteLog(exp, exp.Message);
      }
    }

吸收客戶端數據並播送數據

/// <summary>
    /// 吸收客戶端數據並,轉發到目的客戶端。
    /// </summary>
    public void ReceiveData(object o)
    {
      try
      {
        while (true)
        {
          Socket client = (Socket)o;
          string recvStr = "";
          byte[] recvBytes = new byte[1024];
          int bytes;
          bytes = client.Receive(recvBytes, recvBytes.Length, 0); //從客戶端接收新聞
          recvStr = Encoding.UTF8.GetString(recvBytes, 0, bytes);
          SendMessage(client, recvStr);
          SetText(recvStr);
          CommonFunction.WriteErrorLog(recvStr);
        }
      }
      catch (Exception exp)
      {
        CommonFunction.WriteLog(exp, exp.Message);
      }
    }

斷定是用戶注冊照樣發送新聞

/// <summary>
   /// 斷定是用戶注冊照樣發送新聞
   /// </summary>
   /// <param name="p_strMessage"></param>
   public void SendMessage(Socket client,string p_strMessage)
   {
     if (p_strMessage.StartsWith("@"))
     {
       RegeistUser(p_strMessage, client);
     }
     else if (p_strMessage.StartsWith(">"))
     {
       
       DeleteClident(p_strMessage);
     }
     else
     {
       //SendMessageToTarget(p_strMessage);
       SendAllMessage(p_strMessage);
     }
   }

將socket注冊為指定用戶名

/// <summary>
    /// 將socket注冊為指定用戶名
    /// </summary>
    /// <param name="user"></param>
    /// <param name="ss"></param>
    public void RegeistUser(string user, Socket ss)
    {
      user = user.Remove(0, 1);
      userSocketDict.Add(user, ss);
      SendOneMessage(ss, "迎接" + user + "連入!");
      RefreshClient();
    }

從客戶端字典中移除客戶端

/// <summary>
    /// 從客戶端字典中移除客戶端
    /// </summary>
    /// <param name="p_strMessage"></param>
    public void DeleteClident(string p_strMessage)
    {
      p_strMessage = p_strMessage.Remove(0, 1);
      userSocketDict.Remove(p_strMessage);
      RefreshClient();
    }

群發新聞

/// <summary>
    /// 群發新聞
    /// </summary>
    /// <param name="p_strsend"></param>
    public void SendAllMessage(string p_strsend)
    {
      //MessageBox.Show(p_strsend);
      foreach (string item in userSocketDict.Keys)
      {
        byte[] bs = Encoding.UTF8.GetBytes(p_strsend);
        userSocketDict[item].Send(bs, bs.Length, 0); 
      }
    }

給文本框賦值

public delegate void SetTextHandler(string text);
    /// <summary>
    /// 給文本框賦值
    /// </summary>
    /// <param name="text"></param>
    private void SetText(string text)
    {
      if (rich_back.InvokeRequired == true)
      {
        SetTextHandler set = new SetTextHandler(SetText);//拜托的辦法參數應和SetText分歧 
        rich_back.Invoke(set, new object[] { text }); //此辦法第二參數用於傳入辦法,取代形參text 
      }
      else
      {
        rich_back.Text += "\n" + text;
      }
 
    }

連入辦事器

private void button1_Click(object sender, EventArgs e)
    {
      try
      {
        user = txt_name.Text;
        int port = int.Parse(txt_port.Text);
        string host = txt_ip.Text;
        //創立終結點EndPoint
        IPAddress ip = IPAddress.Parse(host);
        IPEndPoint ipe = new IPEndPoint(ip, port);  //把ip和端口轉化為IPEndPoint的實例
        //創立Socket並銜接到辦事器
        Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  // 創立Socket
        cc = c;
        c.Connect(ipe); //銜接到辦事器
        clientThread = new Thread(new ThreadStart(ReceiveData));
        clientThread.Start();
        //向辦事器發送本機用戶名,以燕服務器注冊客戶端
        SendMessage("@" + txt_name.Text);
      }
      catch (ArgumentException ex)
      {
        Console.WriteLine("argumentNullException:{0}", ex);
      }
      catch (SocketException exp)
      {
        Console.WriteLine("SocketException:{0}",exp);
      }
    }

向辦事器發送新聞

private void button3_Click(object sender, EventArgs e)
    {
      if (""==txt_target.Text)
      {
        MessageBox.Show("未選擇對話人物");
        return;
      }
      //向辦事器發送信息
      string sendStr = txt_name.Text + "@" + target + ":" + txt_message.Text;
      SendMessage(sendStr);
      rch_back.Text += "\n" + sendStr;
      txt_message.Text = "";
    }

隱身

private void button2_Click(object sender, EventArgs e)
    {
      try
      {
        SendMessage(">" + txt_name.Text);
        //cc.Disconnect(true);
        //cc.Shutdown(SocketShutdown.Both);
        //cc.Close();
      }
      catch (Exception exp)
      {
        CommonFunction.WriteLog(exp, exp.Message);
      }
    }

以上所述就是本文的全體內容了,願望年夜家可以或許愛好。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved