欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#实现多线程局域网聊天系统

程序员文章站 2022-06-09 14:12:58
觉得好有点帮助就顶一下啦。 socke编程,支持多客户端,多线程操作避免界面卡死。 开启socket private void button1_click(o...

觉得好有点帮助就顶一下啦。

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

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