




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
第C#使用Socket实现本地多人聊天室本文实例为大家分享了C#使用Socket实现本地多人聊天室的具体代码,供大家参考,具体内容如下
【脚本一:Server端】
使用本机地址:
完整代码
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
usingSystem.Threading;
namespaceConsoleApp1
publicclassServer
{
SocketmySocket=null;
DictionaryIPAddress,SocketcliDic=newDictionaryIPAddress,Socket
publicvoidConnect(intport)
{
stringIP="";
//IPAddressIPAddress=IPAddress.Parse("");
IPAddressaddress=IPAddress.Any;
//创建IP终结点,把IP地址与端口绑定到网络终结点上
IPEndPointendPoint=newIPEndPoint(address,port);
//创建客户端套接字
mySocket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
///监听套接字终结点
mySocket.Bind(endPoint);
//服务端可接收客户端连接数量为无限个
mySocket.Listen(0);
//开启线程监听客户端
ThreadmyThread=newThread(Listen_Con);
myThread.Start();
Console.WriteLine("开始监听...");
}
///summary
///接收连接的客户端并存储客户端的信息
////summary
///paramname="obj"/param
publicvoidListen_Con(Objectobj)
{
SocketcliSocket=null;
//持续监听客户端的请求
while(true)
{
try
{
cliSocket=mySocket.Accept();
}
catch(Exceptione)
{
Console.WriteLine(e.Message);
}
stringcliEndPoint=cliSocket.RemoteEndPoint.ToString();
IPAddresscliAddress=(cliSocket.RemoteEndPointasIPEndPoint).Address;
intcliPort=(cliSocket.RemoteEndPointasIPEndPoint).Port;
cliDic.Add(cliAddress,cliSocket);
stringMsgStr="[客户端结点:"+cliEndPoint+"\n+客户端IP:"+cliAddress.ToString()+"\n客户端端口:"+
cliPort.ToString()+"\n已连接]";
byte[]MsgBytes=Encoding.UTF8.GetBytes(MsgStr);
cliSocket.Send(MsgBytes);
Threadrec_Cli=newThread(Receive_Con);
rec_Cli.Start(cliSocket);
Threadsed_Cli=newThread(SendToCli);
sed_Cli.Start(cliSocket);
}
}
///summary
///接收已连接的客户端发送的消息
////summary
///paramname="socket"/param
publicvoidReceive_Con(Objectsocket)
{
Socketclient=socketasSocket;
while(true)
{
//创建大小为1024*1024的内存缓冲区(1M)
byte[]recBytes=newbyte[1024*1024];
//尝试把接收的字节存储到缓冲区
try
{
intlength=client.Receive(recBytes);
//把机器接收的字节数组转换为string
stringrecMsg=Encoding.UTF8.GetString(recBytes,0,length);
//将服务器接收到的信息转发到所有已连接的客户端
if(cliDic.Count0)
{
foreach(varsocincliDic)
{
soc.Value.Send(Encoding.UTF8.GetBytes("["+soc.Value.RemoteEndPoint+"]:"+recMsg));
}
}
Console.WriteLine("["+client.RemoteEndPoint+"]:"+recMsg);
}
catch(Exception)
{
cliDic.Remove((client.RemoteEndPointasIPEndPoint).Address);
//客户端断开的异常
Console.WriteLine("[客户端"+(client.RemoteEndPointasIPEndPoint).Address+"已断开]");
Console.WriteLine("[客户端终结点:"+client.RemoteEndPoint+"]");
//断开套接字
client.Close();
break;
}
}
}
publicvoidSendToCli(objectobj)
{
SocketcurCliSoc=objasSocket;
while(true)
{
byte[]ByteToAll=newbyte[1024*1024];
try
{
stringMsgToAll=Console.ReadLine();
ByteToAll=Encoding.UTF8.GetBytes("[服务端]:"+MsgToAll);
curCliSoc.Send(ByteToAll);
}
catch(Exception)
{
Console.WriteLine("ERROR:"+curCliSoc.RemoteEndPoint+"已与服务端断开!");
curCliSoc.Close();
if(cliDic.ContainsKey((curCliSoc.RemoteEndPointasIPEndPoint).Address))
{
cliDic.Remove((curCliSoc.RemoteEndPointasIPEndPoint).Address);
}
}
}
}
}
publicclassServerMain
{
staticvoidMain(string[]args)
{
Servers1=newServer();
s1.Connect(8800);
}
}
}
Server端运行结果:
【脚本二:Client端】
完整代码
usingSystem;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
usingSystem.Threading;
namespaceConsoleApp1
publicclassClient
{
stringSerIP="";
SocketmyClient=null;
ThreadConnectThread=null;
IPAddressSerAdd;
IPEndPointSerEP;
publicvoidConnect_To_Ser(intport)
{
myClient=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
SerAdd=IPAddress.Parse(SerIP);
SerEP=newIPEndPoint(SerAdd,port);
while(true)
{
try
{
myClient.Connect(SerEP);
break;
}
catch
{
Console.WriteLine("无法连接到服务端,请重试...");
}
}
ConnectThread=newThread(Receive_Ser);
ConnectThread.Start();
}
publicvoidReceive_Ser()
{
while(true)
{
byte[]SerBytes=newbyte[1024*1024];
try
{
intlength=myClient.Receive(SerBytes);
stringMsg=Encoding.UTF8.GetString(SerBytes,0,length);
Console.WriteLine(Msg);
}
catch(Exception)
{
Console.WriteLine("已与服务端断开连接...");
break;
}
}
}
publicvoidSendToSer()
{
while(true)
{
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2024年南平市第二医院招聘笔试真题
- 有效的内容营销策略计划
- 2025年软考设计师核心框架试题及答案
- VB编程与企业数字化改革的联系题及答案
- 网络管理工具应用试题及答案
- 风险管理与合规性考察试题及答案
- 山东省淄博市周村区2025年七下数学期末经典模拟试题含解析
- 助力企业提升技术能力的建议试题及答案
- 男女平等法律地位的演变试题及答案
- 2025届重庆市渝北八中学数学七下期末达标检测模拟试题含解析
- 关爱生命-健康成长家安全教育家长会课件
- 公司经营管理手册目录
- 基础会计练习题及答案
- 限高杆施工图 2
- 5万吨钢筋加工配送中心项目
- 初中数学北师大九年级下册 直角三角形的边角关系谢荣华 教学设计《锐角三角函数》
- 机房空调升级改造方案
- 老年患者营养支持途径及配方选择课件
- 二环庚二烯(2,5-降冰片二烯)的理化性质及危险特性表
- 【审计工作底稿模板】FK长期借款
- arcgis网络分析.
评论
0/150
提交评论