Scoket编程--UDP
来源:互联网 发布:apache 开源框架 编辑:程序博客网 时间:2024/05/29 17:37
以聊天的交互方式为例,,注意要开两个VS,先运行服务端,,,
服务器代码:
using System;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;namespace _002_Stcket_UDP服务端{ class Program { public static Socket udpServer; static void Main(string[] args) { //1, 创建 udpServer = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); //2,绑定ip udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.11"), 3355)); //3,接收数据 //设为后台线程并且开启线程 Console.WriteLine("服务器开始成功:"); new Thread(ReceiveMessage) { IsBackground = true }.Start(); //关闭就无法无限接收数据 //udpServer.Close(); Console.ReadKey(); } /// <summary> /// 接收数据 /// </summary> static void ReceiveMessage() { while (true) { EndPoint remoteEndpoint = new IPEndPoint(IPAddress.Any, 0); //实例化一个空的ip:port byte[] data = new byte[1024]; //接收字符的数组 //此方法,会把数据的来源(Ip+端口号)放到第二个参数上 int length = udpServer.ReceiveFrom(data, ref remoteEndpoint); string message = Encoding.UTF8.GetString(data,0,length); Console.WriteLine("从ip" + (remoteEndpoint as IPEndPoint).Address + ":" + (remoteEndpoint as IPEndPoint).Port + "接收数据: "+ message); } } }}
客户端代码:
using System;using System.Net;using System.Net.Sockets;using System.Text;namespace _002_Socet_DUP客户端{ class Program { static void Main(string[] args) { //创建Scoket (不用刻意记住,都是枚举,根据构造函数选取需要的就行了) Socket udpClient = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); while (true) { //发送数据 SendTo(要发消息转换的字节数组,端口号和ip地址) EndPoint severEndpoint = new IPEndPoint(IPAddress.Parse("192.168.1.11"), 3355); string message = Console.ReadLine(); byte[] data = Encoding.UTF8.GetBytes(message); udpClient.SendTo(data, severEndpoint); Console.WriteLine("消息已发出,输入p退出:--------"); if (message == "p") { break; } } udpClient.Close(); Console.ReadKey(); } }}
运行示例:
阅读全文
1 0
- Scoket编程--UDP
- Scoket编程基础及tcp&udp的简介And区别
- scoket编程
- Scoket 编程
- Scoket编程
- Scoket编程
- Scoket:UDP通讯模型
- UDP的Scoket
- java通信之Scoket-UDP
- TCP/IP Scoket编程之UDP聊天室(C语言实现)
- java scoket 编程实例
- Linux ScoKet编程
- C++ Scoket编程
- C++ Scoket编程
- VC++ Scoket编程小结
- 网络编程scoket
- 【Scoket编程】篇二
- Scoket网络编程客户端
- 滑动后自动加载基础详解OnScrollListener
- Dynamic Frameworks
- shader实例(三)物体描边
- java线程池和队列
- 再见了,城堡
- Scoket编程--UDP
- android 三级界面返回直接到一级界面
- 行人属性“Weakly-supervised Learning of Mid-level Features for Pedestrian Attribute Recognition and Loca”
- 20.Container With Most Water
- 6、用vue2.0extend写alert模态框弹窗组件
- 常用的JVM参数记录
- C
- Linux下的crontab定时执行任务命令详解
- STL 源码分析之string(一)基础篇