一、关于UDP
1.套接字(socket)
所谓套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制。从所处的地位来讲,套接字上联应用进程,下联网络协议栈,是应用程序通过网络协议进行通信的接口,是应用程序与网络协议根进行交互的接口。
2、UDP
nternet 协议集支持一个无连接的传输协议,该协议称为用户数据报协议(UDP,User Datagram Protocol)。UDP 为应用程序提供了一种无需建立连接就可以发送封装的 IP 数据包的方法。UDP协议与TCP协议一样用于处理数据包,在OSI模型中,两者都位于传输层,处于IP协议的上一层。UDP有不提供数据包分组、组装和不能对数据包进行排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的。UDP用来支持那些需要在计算机之间传输数据的网络应用。包括网络视频会议系统在内的众多的客户/服务器模式的网络应用都需要使用UDP协议。UDP协议从问世至今已经被使用了很多年,虽然其最初的光彩已经被一些类似协议所掩盖,但即使在今天UDP仍然不失为一项非常实用和可行的网络传输层协议
二、C#项目创建
1.类型选择
1.窗口应用程序
2.选择存储位置
3.
直接就开始了
三、C#UDP通信程序编写
客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Udp_Client
{
class Program
{
static void Main(string[] args)
{
string sendString = null;//要发送的字符串
byte[] sendData = null;//要发送的字节数组
UdpClient client = null;
IPAddress remoteIP = IPAddress.Parse("192.168.31.57"); //假设发送给这个IP
int remotePort = 11001;
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点
sendString = Console.ReadLine();
string sum="";
for (int i = 0; i < 50; i++)
sum = sum + sendString + i + "\n";
sendData = Encoding.Default.GetBytes(sum);
client = new UdpClient();
client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
String message = Encoding.Default.GetString(client.Receive(ref remotePoint));
Console.WriteLine(message);
Console.Read();
client.Close();//关闭链接
}
}
}
服务端:
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace Project1
{
class Class2
{
static void Main(string[] args)
{
UdpClient client = null;
string receiveString = null;
byte[] receiveData = null;
//实例化一个远程端点,IP和端口可以随意指定,等调用client.Receive(ref remotePoint)时会将该端点改成真正发送端端点
IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
client = new UdpClient(11001);
receiveData = client.Receive(ref remotePoint);//接收数据
Encoding encodingUTF8 = new UTF8Encoding(true);
receiveString = Encoding.Default.GetString(receiveData);
client.Send( receiveData, receiveData.Length, remotePoint);
Console.WriteLine(receiveString);
client.Close();//关闭连接
}
}
}
}
四、结果显示
客户端模式也是一样的,客户端怎么写可以参考我以前的博客.
五、wireshark抓包
六、小结
C#语法入门不是很难,但是学海无涯,还得继续加油。
本次UDP套接字实验和wireshark抓包分析很有议席
七、资料引用
基于C#的UDP协议的同步实现
C#使用 UdpClient 类进行简单通信的例子
c# 实现简单udp数据的发送和接收