首页 > 编程 > 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);      }    }

以上所述就是本文的全部内容了,希望大家能够喜欢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表