国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

c#實現多線程局域網聊天系統

2020-01-24 01:47:32
字體:
來源:轉載
供稿:網友

覺得好有點幫助就頂一下啦。

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

以上所述就是本文的全部內容了,希望大家能夠喜歡。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 涟源市| 浮山县| 抚州市| 西和县| 蒲城县| 涡阳县| 迭部县| 东城区| 南京市| 谷城县| 马尔康县| 正镶白旗| 贵阳市| 泸溪县| 东光县| 浑源县| 定结县| 石门县| 九台市| 梁河县| 吉首市| 石渠县| 西平县| 敖汉旗| 新干县| 安龙县| 曲水县| 长宁县| 加查县| 钟山县| 鲁山县| 台州市| 胶州市| 迁安市| 会理县| 娄烦县| 汽车| 庆云县| 霍山县| 温宿县| 巨鹿县|