首页 > 作文

C#使用Socket实现本地多人聊天室

更新时间:2023-04-04 23:48:38 阅读: 评论:0

本文实例为大家分享了c#使用socket实现本地多人聊天室的具体代码,供大家参考,具体内容如下

【脚本一:rver端】

使用本机地址:127.0.0.1

完整代码

using system;using system.collections.generic;using system.net;using system.net.sockets;using system.text;using system.threading;namespace consoleapp1{ public class rver {  socket mysocket = null;  dictionary<ipaddress, socket> clidic = new dictionary<ipaddress, socket>();  public void connect(int port)  {   string ip = "127.0.0.1";   //ipaddress ipaddress = ipaddress.par("127.0.0.1");   ipaddress address = ipaddress.any;   //创建ip终结点,把ip地址与端口绑定到网络终结点上   ipendpoint endpoint = new ipendpoint(address, port);   //创建客户端套接字   mysocket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);   ///监听套接字终结点   mysocket.bind(endpoint);   //服务端可接收客户端连接数量为无限个   mysocket.listen(0);   //开启线程监听客户端   thread mythread = new thread(listen_con);   mythread.start();   console.writeline("开始监听...");  }  /// <summary>  /// 接收连接的客户端并存储客户端的信息  /// </summary>  /// <param name="obj"></param>  public void listen_con(object obj)  {   socket clisocket = null;   //持续监听客户端的请求   while (true)   {    try    {     clisocket = mysocket.accept();    }    catch (exception e)    {     console.writeline(e.message);    }    string cliendpoint = clisocket.remoteendpoint.tostring();    ipaddress cliaddress = (clisocket.remoteendpoint as ipendpoint).address;    int cliport = (clisocket.remoteendpoint as ipendpoint).port;    clidic.add(cl高二数学试卷iaddress, clisocket);    string msgstr = "[客户端结点:" + cliendpoint + "\n+客户端ip:" + cliaddress.tostring() + "\n客户端端口:" +     cliport.tostring() + "\n已连接]";    byte[] msgbytes = encoding.utf8.getbytes(msgstr);    clisocket.nd(msgbytes);    thread rec_cli = new thread(receive_con);    rec_cli.start(clisocket);    thread d_cli = new thread(ndtocli);    d_cli.start(clisocket);   }  }  /// <summary>  /// 接收已连接的客户端发送的消息  /// </summary>  /// <param name="socket"></param>  public void receive_con(object socket)  {   socket client = socket as socket;   while (true)   {    //创建大小为1024*1024的内存缓冲区(1m)    byte[] recbytes = new byte[1024 * 1024];    //尝试把接收的字节存储到缓冲区    try    {     int length = client.receive(recbytes);     //把机器接收的字节数组转换为string     string recmsg = encoding.utf8.getstring(recbytes, 0, length);     //将服务器接收到的信息转发到所有已连接的客户端     if (clidic.count > 0)     {      foreach (var soc in clidic)      {       soc.value.nd(encoding.utf8.getbytes("[" + soc.value.remoteendpoint + "]:" + recmsg));      }     }     console.writeline("[" + client.remoteendpoint + "]:" + recmsg);    }    catch (exception)    {     clidic.remove((client.remoteendpoint as ipendpoint).address);     //客户端断开的异常   火把节哪个民族  console.writeline("[客户端" + (client.remoteendpoint as ipendpoint).address + "已断开]");     console.writeline("[客户端终结点:" + client.remoteendpoint+"]");     //断开套接字     client.clo();     break;    }   }  }  public void ndtocli(object obj)  {   socket curclisoc = obj as socket;   while (true)   {    byte[] bytetoall = new byte[1024 * 1024];    try    {     string msgtoall = console.readline();     bytetoall = encoding.utf8.getbytes("[服务端]:"+msgtoall);     curclisoc.nd(bytetoall);    }    catch(exception)    {     console.writeline("error:" + curclisoc.remoteendpoint + "已与服务端断开!");     curclisoc.clo();     if(clidic.containskey((curclisoc.remoteendpoint as ipendpoint).address))     {      clidic.remove((curclisoc.remoteendpoint as ipendpoint).address);     }    }   }  } } public class rvermain {  static void main(string[] args)  {   rver s1 = new rver();   s1.connect(8800);  } }}

rver端运行结果:

【脚本二:client端】

完整代码

using system;using system.net;using system.net.sockets;using system.text;using system.threading;namespace consoleapp1{ public class client {  string rip = "127.0.0.1";  socket myclient = null;  thread connectthread = null;  ipaddress radd;  ipendpoint rep;  public void connect_to_r(int port)  一牛顿等于多少克{   myclient = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);   radd = ipaddress.par(rip);   rep = new ipendpoint(radd, port);   while (true)   {    try    {     myclient.connect(rep);     break;    }    catch    {     console.writeline("无法连接到服务端,请重试...");    }   }   connectthread = new thread(receive_r);   connectthread.start();  }  public void receive_r()  {   while (true)   {    byte[] rbytes = new byte[1024 * 1024];    try    {     int length = myclient.receive(rbytes);     string msg = encoding.utf8.getstring(rbytes, 0, length);     console.writeline(msg);    }    catch (exception)    {     console.writeline("已与服务端断开连接...");     break;    }   }  }  public void ndtor()  {   while (true)   {    try    {     string ndmsg = consol辞海打一成语e.readline();     myclient.nd(encoding.utf8.getbytes(ndmsg));    human复数}    catch (exception)    {     console.writeline("[ndtor]已断开连接");     break;    }   }  } } public class clienmain {  static void main(string[] args)  {   client c1 = new client();   c1.connect_to_r(8800);   c1.ndtor();  } }}

客户端运行效果:

①客户端先于服务端运行

②客户端迟于服务端运行

暂时总效果:

功能完善:

①客户端连上服务端后若服务端断开再打开,客户端无法重连

②心跳包重连

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。

本文发布于:2023-04-04 23:48:36,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/d628bc7c3457b80eb2490ce00dc047c8.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:C#使用Socket实现本地多人聊天室.doc

本文 PDF 下载地址:C#使用Socket实现本地多人聊天室.pdf

标签:客户端   服务端   缓冲区   代码
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图