一、控制台程序使用 UDP 通信
1)创建新项目
打开 VS2019 ,点击 “ 创建新项目 ”
创建完成如下:
2)编写代码
在控制台上简单输出:
在 Main 函数内书写如下的代码(功能:连续输出 50 行数据)。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 50; i++)
{
Console.WriteLine("第{0}行:hello cqjtu!重交物联2018级", (i + 1));
}
System.Console.ReadKey();
}
}
}
编译结果如下:
使用 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 Client
{
class Program
{
static void Main(string[] args)
{
//提示信息
Console.WriteLine("按下任意按键开始发送...");
Console.ReadKey();
int m;
//做好链接准备
UdpClient client = new UdpClient(); //实例一个端口
IPAddress remoteIP = IPAddress.Parse("10.60.202.32"); //假设发送给这个IP
int remotePort = 11000; //设置端口号
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort); //实例化一个远程端点
for(int i = 0; i < 50; i++)
{
//要发送的数据:第n行:hello cqjtu!重交物联2018级
string sendString = null;
sendString += "第";
m = i+1;
sendString += m.ToString();
sendString += "行:hello cqjtu!重交物联2018级";
//定义发送的字节数组
//将字符串转化为字节并存储到字节数组中
byte[] sendData = null;
sendData = Encoding.Default.GetBytes(sendString);
client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
}
client.Close();//关闭连接
//提示信息
Console.WriteLine("");
Console.WriteLine("数据发送成功,按任意键退出...");
System.Console.ReadKey();
}
}
}
在旁边室友电脑上新建项目
生成服务端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Server
{
class Program
{
static void Main(string[] args)
{
int result;
string str = "第50行:hello cqjtu!重交物联2018级";
UdpClient client = new UdpClient(11000);
string receiveString = null;
byte[] receiveData = null;
//实例化一个远程端点,IP和端口可以随意指定,等调用client.Receive(ref remotePoint)时会将该端点改成真正发送端端点
IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("正在准备接收数据...");
while (true)
{
receiveData = client.Receive(ref remotePoint);//接收数据
receiveString = Encoding.Default.GetString(receiveData);
Console.WriteLine(receiveString);
result = String.Compare(receiveString, str);
if (result == 0)
{
break;
}
}
client.Close();//关闭连接
Console.WriteLine("");
Console.WriteLine("数据接收完毕,按任意键退出...");
System.Console.ReadKey();
}
}
}
编译结果如下:
客户端:

服务端:

4)抓包分析数据
在桌面双击打开之前下载的 Wireshark 。
由于我使用的网线连接,所以是通过以太网通信的,双击 “ 以太网 ”。
可以看到现在 Wireshark 不断的在抓包,先点击红色的按钮暂停抓包。
重新编译客户端和服务器端,先不要按下按键发送数据,先挂着,看下一步。
点击鲨鱼鱼鳍的图标,然后点击 “ Continue without Saving ”,不保存之前抓取的包。
然后按键盘开始发送数据,发送完后,点击 Wireshark 的红色按钮,停止抓包。
在方框内输入 “ UDP ” 过滤包,然后就可以看到下面的信息,这些就是我发送给我室友电脑上的 50 条数据,下面开始分析这些数据,只选择其中一条分析。
版权声明:本文为weixin_44439920原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。