• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#socket简单例子

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

打开命名空间

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 }

参考博客园文章



鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
黄聪:c#水晶报表的进一步功能和使用发布时间:2022-07-13
下一篇:
Lua调用c#发生了什么?发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap