基于Udp协议是无连接模式通讯,占用资源少,响应速度快,延时低。至于可靠性,可通过应用层的控制来满足。(不可靠连接)

使用Udp协议通讯需要具备以下几个条件:

(1).建立一个套接字(Socket)

(2).绑定服务器端IP地址及端口号--服务器端

(3).通过SendTo()方法向指定主机发送消息     (需提供主机IP地址及端口)

(4).通过ReciveFrom()方法接收指定主机发送的消息     (需提供主机IP地址及端口)

下面用代码实现简单的服务器---客户端通信

服务器端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace _023_socket编程_UDP协议_服务器端 {
class Program
{
private static Socket udpServer;
static void Main(string[] args) {
//1,创建socket
udpServer = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
//2,绑定ip跟端口号
udpServer.Bind( new IPEndPoint( IPAddress.Parse("192.168.1.101"),7788 ) ); //3,接收数据
new Thread(ReceiveMessage){ IsBackground = true}.Start();
Console.WriteLine("服务器启动...");
Console.ReadKey();
} static void ReceiveMessage()
{
while (true)
{
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);//这个方法会把数据的来源(ip:port)放到第二个参数上
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("从ip:" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port + "收到了数据:" + message);
} }
}
}

客户端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks; namespace _002_socket编程_udp协议_客户端 {
class Program {
static void Main(string[] args) {
//创建socket
Socket udpClient = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp); while (true)
{
//发送数据
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.1.101"), 7788);
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
udpClient.SendTo(data, serverPoint);
} udpClient.Close();
Console.ReadKey();
}
}
}

执行过程:

(1)启动服务器

(2)启动客户端,并向服务器发送数据

最新文章

  1. ASP.NET Core 折腾笔记一
  2. 用jquery实现瀑布流案例
  3. 优化MySQL数据库性能的八大方法
  4. Roslyn词法分析器初使用
  5. JS的基础知识
  6. iOS7程序内部如何打开评分页面
  7. PHP判断用户所在国家并跳转对应的目录
  8. Winform设置相关
  9. js判断加载大小页面
  10. [Everyday Mathematics]20150104
  11. hdoj 3785 寻找大富翁【优先队列+sort排序】
  12. 【转】Spring注解@Component、@Repository、@Service、@Controller区别
  13. 关于各种数据库 Insert时同时取到Id的操作
  14. WebService 调用三种方法
  15. Unsupervised Learning and Text Mining of Emotion Terms Using R
  16. Gym 100963B
  17. 用Quartz 2D画小黄人
  18. BZOJ 1874 取石子游戏 - SG函数
  19. SW-DP (Serial Wire Debug Port) Analyzer plugin for the Saleae Logic
  20. C#多线程JOIN方法初探

热门文章

  1. Linux( Ubantu ) 的简单使用
  2. 小程序生成海报 canvas
  3. Hadoop-No.7之行键
  4. Win7安装VS2019
  5. centos后台运行python程序
  6. python-日常用法小记
  7. 学号 20175329 《Java程序设计》第10周学习总结
  8. 移动端隐藏scroll滚动条::-webkit-scrollbar
  9. SpringMVC @ResponseBody返回中文乱码
  10. MVC中上传文件