简单的C#socket例子(转载)
打开命名空间
using System.Net;
using System.Net.Sockets;
服务端代码:
1 static void Main(string[] args)
2 {
3 int port = 2000;
4 string host = "127.0.0.1";
5
6 IPAddress ip = IPAddress.Parse(host);
7 IPEndPoint ipe = new IPEndPoint(ip, port);
8
9 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
10 socket.Bind(ipe);
11 socket.Listen(0); //监听
12 Console.WriteLine("waiting.......");
13
14 //接受来自客户端发送的信息
15 Socket temp = socket.Accept(); //创建新的socket用于和客户端通信
16 Console.WriteLine("ok...");
17 string recstr = "";
18 byte[] recbyte = new byte[1024];
19 int bytes;
20 bytes = temp.Receive(recbyte, recbyte.Length, 0);
21 recstr += Encoding.ASCII.GetString(recbyte, 0, bytes);
22
23 //给客户端返回信息
24 Console.WriteLine("server get message:{0}", recstr);
25 string sendstr = "client send message successful";
26 byte[] by = Encoding.ASCII.GetBytes(sendstr);
27 temp.Send(by, by.Length, 0); //发送
28 temp.Close(); //关闭
29 socket.Close();
30 Console.ReadLine();
31
32 }
客户端代码:
1 static void Main(string[] args)
2 {
3 try
4 {
5 int port = 2000;
6 string host = "127.0.0.1";
7
8 IPAddress ip = IPAddress.Parse(host);
9 IPEndPoint iped = new IPEndPoint(ip, port);
10
11 Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
12 Console.WriteLine("waiting......");
13 soc.Connect(iped); //连接
14
15 //向服务端发送消息
16 string sendstr = "hello,this is client message";
17 byte[] bytes = Encoding.ASCII.GetBytes(sendstr);
18 Console.WriteLine("send message");
19 soc.Send(bytes);
20
21 //接受由服务端返回的信息
22 string recstr = "";
23 byte[] recbyte = new byte[1024];
24 int bytess;
25 bytess = soc.Receive(recbyte, recbyte.Length, 0);
26 recstr += Encoding.ASCII.GetString(recbyte, 0, bytess);
27 Console.WriteLine("get message:{0}", recstr);
28 soc.Close();
29
30 }
31 catch (Exception ex)
32 {
33 Console.WriteLine("error");
34 }
35 Console.WriteLine("press enter exit");
36 Console.ReadLine();
37 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗