socket简单demo
Server、Client端分别在两个项目中
Server端:
try
{
int port = 4000;
string host = "127.0.0.1";
IPAddress ipa = IPAddress.Parse(host);//将IP字符串转换为IP地址的实例
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, port);//将网络端点表示为ip地址和端口号 允许任意IP
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket类
s.Bind(ipe);//绑定端口号
s.Listen(0);//开始监听
Console.WriteLine("wait for connect");
Socket tmp = s.Accept();//为新连接创建新的socket
Console.WriteLine("get a connect");
while (true)
{
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = tmp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接收信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine("get message:{0}", recvStr);//把从客户端传来的信息显示出来
string sendStr = "Yeah! Client send message sucessful";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
tmp.Send(bs, bs.Length, 0);//返回客户端成功信息
//tmp.Close();
//s.Close();
}
}
catch (ArgumentNullException ex)
{
Console.WriteLine(ex);
}
catch (SocketException ex)
{ Console.WriteLine(ex); }
Console.WriteLine("press enter to exit");
Console.ReadLine();
Client端:
try
{
int port = 4000;
string host = "127.0.0.1";
IPAddress ipa = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ipa, port);//把ip和端口转化为ipendpoint实例
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket
Console.WriteLine("connecting.....");
s.Connect(ipe);//连接到服务器
while (true)
{
Console.WriteLine("请输入要发送的信息:");
string sendStr = Console.ReadLine();
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
Console.WriteLine("SendMessage");
s.Send(bs, bs.Length, 0);//发送测试信息
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = s.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接收返回信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine("ClientGetMessage:{0}/r/n/r/n", recvStr);//显示服务器返回信息
//s.Close();
}
}
catch (ArgumentNullException ex)
{ Console.WriteLine(ex); }
catch (SocketException ex)
{ Console.WriteLine(ex); }
Console.WriteLine("press enter to exit");
Console.ReadLine();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)