目的
- 用C#编写一个命令行/控制台hello world程序,实现如下功能:在屏幕上连续输出50行“hello cqjtu!重交物联2018级”;同时打开一个网络UDP 套接字,向室友电脑发送这50行消息。
- 用C#编写一个简单的Form窗口程序,有一个文本框 textEdit和一个发送按钮button,运行程序后,可以在文本框里输入文字,如“hello cqjtu!重交物联2018级”,点击button,将这些文字发送给室友电脑,采用UDP套接字;
- 安装wireshark 抓包软件,抓取上述程序发送的网络包,对数据帧结构进行分析。
一、C#控制台程序
1.代码实现
1)客户端client(数据发送)
目前最普遍的服务模式是 C/S 模式,所以需要一个客户端 client 和一个服务端 Server ,来实现通信。
将我的电脑当做客户端,将舍友电脑当做服务端,分别运行对应的代码即可实现数据的传输与接收。
打开VS2017选择新建项目
写入以下代码
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.190.149"); //接收方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();
}
}
}
注意代码中的IP地址
在接收方设备中打开cmd并执行ipconfig命令可查得其IP地址
2)服务端Server(数据接收)
在舍友的电脑中新建一个同样的VS2017项目
写入以下代码:
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();
}
}
}
3)编译结果
客户端Client:
服务端Server:
2.Wireshark抓包
1)抓包
我电脑使用的网线连接,双击【以太网】
Wireshark在一直抓包,先点击左上红色按钮暂停抓包
重新编译客户端和服务器端,先不发送数据,在Wireshark中点击鱼鳍图标,然后选择【Continue without Saving】,不保存之前抓取的包。
然后客户端按下按键发送数据,发送完后同样点击红色按钮停止抓包
2)数据分析
在Wireshark上面方框中输入UDP进行过滤,可以看到下面给室友发的数据,选择其中一条分析。
打开一条数据,选中Ehternet,这就是数据链路层的帧头部,响应的下面蓝色部分的十六进制,就是对应的数据。
帧的头部:
- 目的地址Destination(6字节):数据的接收方,这里是:10.60.190.149
- 源地址Source(6字节):数据的发送方,这里是:10.60.191.222
- 数据类型Type(2字节):分为 IP(0800) 包和 ARP(0806) 包,这个包是 0800 ,所以是 IP 包。
- 数据:后面三排,上层(网络层)传下来的一个 IP 包,数据部分又分为数据部分和填充部分,数据(数据部分 + 填充部分)的长度最长为 1500 个字节,不能过大,所以帧的总长度最长为 1518 字节,抓取的所有包,都不会超过这个长度。
- 校验码(4字节):帧的末尾有4字节的校验码,但抓包软件会自动舍弃
数据包:
数据长度为34字节,这就是发送的数据。
二、C#Form窗口程序
1.项目与控件
创建一个窗体应用项目
在左侧工具栏中找到Button和TextBox控件,拖到窗口中并进行排版
注意TextBox控件右上角的黑色三角形可以选择MultiLine将其置于多行文本的模式中
发送按钮属性设置:
选择button1,可在右下角属性设置中的Text改变显示的文本
然后还可在看到这个按钮的name是button1
这是它的标识
消息显示界面属性设置:
选择界面,在属性中找到ScrollBars增加垂直滚动条
设置边界,在属性中知道到BorderStyle设置为FixedSingle
设置文本框不可编辑
它的name是textBox2
窗体属性设置
单击窗体选中,在右下角将Text属性改为“客户端”,然后将AcceptButton属性下拉框选中button1按钮,这个设置可以使得我们运行程序时,按下回车键=点击button1
控件属性设置完成
2.代码实现
1)客户端
只要在窗体界面中双击某个控件,vc2017将会自动跳转至对应控件的函数中去
双击窗体,进入函数页面,写入以下代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
try
{
/*
* 显示当前时间
*/
string str = "The current time: ";
str += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
textBox2.AppendText(str + Environment.NewLine);
/*
* 做好连接准备
*/
int port = 2000;
string host = "10.60.190.149";//我室友的IP地址
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
/*
* 开始连接
*/
str = "Connect to server...";
textBox2.AppendText(str + Environment.NewLine);
c.Connect(ipe);//连接到服务器
/*
*发送消息
*/
string sendStr = textBox1.Text;
str = "The message content: " + sendStr;
textBox2.AppendText(str + Environment.NewLine);
byte[] bs = Encoding.UTF8.GetBytes(sendStr);
str = "Send the message to the server...";
textBox2.AppendText(str + Environment.NewLine);
c.Send(bs, bs.Length, 0);//发送信息
/*
* 接收服务器端的反馈信息
*/
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
str = "The server feedback: " + recvStr;//显示服务器返回信息
textBox2.AppendText(str + Environment.NewLine);
/*
* 关闭socket
*/
c.Close();
}
catch (ArgumentNullException f)
{
string str = "ArgumentNullException: " + f.ToString();
textBox2.AppendText(str + Environment.NewLine);
}
catch (SocketException f)
{
string str = "ArgumentNullException: " + f.ToString();
textBox2.AppendText(str + Environment.NewLine);
}
textBox2.AppendText("" + Environment.NewLine);
textBox1.Text = "";
}
}
}
同样的,要注意修改ip地址
2)服务端
与之前,在舍友电脑上用vc2017创建一个控制台程序,写入以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
/*
* 做好连接准备
*/
int i = 0;
int port = 2000;
string host = "10.60.202.32";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket类
s.Bind(ipe);//绑定2000端口
/*
* 循环监听并处理消息
*/
while (true)
{
i++;
try
{
Console.Write("Perform operations {0} :",i);
Console.WriteLine("\t-----------------------------------------------");
s.Listen(0);//开始监听
Console.WriteLine("1. Wait for connect...");
/*
* 实例一个新的socket端口
*/
Socket temp = s.Accept();//为新建连接创建新的Socket。
Console.WriteLine("2. Get a connect");
/*
* 接收客户端发的消息并做解码处理
*/
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
Console.WriteLine("3. Server Get Message:{0}", recvStr);//把客户端传来的信息显示出来
/*
* 返回给客户端连接成功的消息
*/
string sendStr = "Ok!Client send message sucessful!";
byte[] bs = Encoding.UTF8.GetBytes(sendStr);
temp.Send(bs, bs.Length, 0);//返回客户端成功信息
/*
* 关闭端口
*/
temp.Close();
Console.WriteLine("4. Completed...");
Console.WriteLine("-----------------------------------------------------------------------");
Console.WriteLine("");
//s.Close();//关闭socket(由于再死循环中,所以不用写,但如果是单个接收,实例socket并完成任务后需关闭)
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
}
}
}
}
3.错误信息
正常来说成功做到这一步,就可以在客户端的form窗口输入要发送的消息,再点击发送按钮,舍友电脑上的服务端就能接收到信息。参考博客
然而当客户端Form程序编译时却报了以下错误:
而当我参考舍友的博客后,客户端Form程序编译时又报了另一个错误:
我既从网上查找相关博客和资料,也尝试过在代码中纠错,但奈何本人能力不足,程序中的报错一直没有找到解决的方法,没法完成程序的编译和运行,也没法展示程序运行的效果。
三、总结
就结果来说并不完美,C#控制台程序能有不错的完成度,实现了数据的传输和Wireshark的抓包分析,但是后面Form窗口程序编译错误找不到解决方法,没法完成实验,且很可惜后续的抓包和对比也没法完成了。😦
四、参考
①C#使用TCP/UDP协议通信并用Wireshark抓包分析数据
②c# 实现简单udp数据的发送和接收
③wireshark抓包分析——TCP/IP协议
④C# udp简单使用