UDP单播通信测试案例C#
UDP单播
一段代码做纪念
Client
// An highlighted block
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using CRC;
namespace CRC
{
public partial class MainForm : Form
{
private IPEndPoint ServerInfo;
private Socket ClientSocket;
private EndPoint Remote;
//信息接收缓存
private Byte[] MsgBuffer;
//信息发送存储
private Byte[] MsgSend;
byte[] data = new byte[1024];
string input, stringData;
private Thread CThread;//服务端运行的线程
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
//this.CmdSend.Enabled = false;
//this.CmdExit.Enabled = false;
MsgBuffer = new Byte[65535];
MsgSend = new Byte[65535];
//允许子线程刷新数据
CheckForIllegalCrossThreadCalls = false;
Userport.Text = "6888";
UserIP.Text = "192.168.10.4";
//127.0.0.1是回环地址,用于测试本机内连接
//192.168.10.4用来发到其他的主机上
}
bool flag = true;//定义一个bool变量,标识是否接收数据
Thread thread;//创建线程对象
UdpClient udp;
private void CmdEnter_Click(object sender, EventArgs e)
{
this.CmdEnter.Enabled = false;
this.CmdExit.Enabled = true;
//设置服务IP,设置TCP端口号
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(this.UserIP.Text), 6888);
//定义网络类型,数据连接类型和网络协议UDP
Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello! ";
data = Encoding.Unicode.GetBytes(welcome);
ClientSocket.SendTo(data, data.Length, SocketFlags.None, ipep);
IPEndPoint sder = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sder;
data = new byte[1024];
//对于不存在的IP地址,加入此行代码后,可以在指定时间内解除阻塞模式限制
//server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100);
int recv = ClientSocket.ReceiveFrom(data, ref Remote);
this.ReceiveMsg.AppendText("Message received from "+Remote.ToString());
this.ReceiveMsg.AppendText(Encoding.Unicode.GetString(data, 0, recv));
flag = true;//标识接收数据
thread = new Thread(() =>//新开线程,执行接收数据操作
{
while (flag)//如果标识为true
{
try
{
input = "123456789";
ClientSocket.SendTo(Encoding.Unicode.GetBytes(input), Remote);
data = new byte[1024];
recv = ClientSocket.ReceiveFrom(data, ref Remote);
stringData = Encoding.Unicode.GetString(data, 0, recv);
this.ReceiveMsg.AppendText(stringData+"\n");
string OnePareStr = stringData.Substring(0,4);
string TwoPareStr = stringData.Substring(4,4);
string ThreePareStr = stringData.Substring(8, 4);
string FourPareStr = stringData.Substring(12, 4);
string FivePareStr = stringData.Substring(16, 4);
string deData = Decode(OnePareStr, TwoPareStr, ThreePareStr, FourPareStr, FivePareStr);
this.ReceiveMsg.AppendText(deData + "\n");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);//错误提示
}
//Thread.Sleep(2000);//线程休眠2秒
}
});
thread.Start();//启动线程
}
private string Decode(string onePareStr, string twoPareStr, string threePareStr, string fourPareStr, string fivePareStr)
{
string mycode, myc0, myc1, myc2, myc3, myc4;
Int16 id0, id1, id2, id3, id4;
id0=System.Convert.ToInt16(onePareStr, 16);
id1=System.Convert.ToInt16(twoPareStr, 16);
id2=System.Convert.ToInt16(threePareStr, 16);
id3=System.Convert.ToInt16(fourPareStr, 16);
id4=System.Convert.ToInt16(fivePareStr, 16);
switch (id0){
case 2:
myc0 = "进站触发";
break;
default:
myc0 = "";
break;
}
switch (id1)
{
case 1:
myc1 = "阎村东";
break;
default:
myc1 = "阎村东";
break;
}
switch (id2)
{
case 1:
myc2 = "阎村东";
break;
default:
myc2 = "阎村东";
break;
}
switch (id3)
{
case 2:
myc3 = "紫草坞";
break;
default:
myc3 = "紫草坞";
break;
}
switch (id4)
{
case 20:
myc4 = "燕山";
break;
default:
myc4 = "燕山";
break;
}
mycode = myc0+ ",起始站" + myc1 + ",当前站" + myc2 + ",下一站" + myc3 + ",终点站" + myc4;
return mycode;
}
private void CmdExit_Click(object sender, EventArgs e)
{
ClientSocket.Close();
this.CmdEnter.Enabled = true;
this.CmdExit.Enabled = false;
}
}
}
Server
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace Server
{
public partial class MainForm : Form
{
//声明将要用到的类
private IPEndPoint ServerInfo;//存放服务器的IP和端口信息
private EndPoint Remote;
private Socket ServerSocket;//服务端运行的SOCKET
private Thread ServerThread;//服务端运行的线程
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
this.CmdStar.Enabled = true;
this.CmdStop.Enabled = false;
ServerIP.Text= "192.168.10.4";
RemoteIp.Text= "192.168.10.5";
}
// udp.Connect("127.0.0.1", 6888);//127.0.0.1是回环地址,用于测试本机内连接
//udp.Connect("192.168.1.255", 6888);//192.168.10.5用来发到其他的主机上
private void CmdStar_Click(object sender, EventArgs e)
{
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//提供一个 IP 地址,指示服务器应侦听所有网络接口上的客户端活动
ServerInfo = new IPEndPoint(IPAddress.Parse(this.ServerIP.Text), Convert.ToInt32(ServerPort.Text));
ServerSocket.Bind(ServerInfo);//将SOCKET接口和IP端口绑定
ServerThread = new Thread(new ThreadStart(RecieveAccept));//将接受客户端连接的方法委托给线程
ServerThread.Start();//线程开始运行
CheckForIllegalCrossThreadCalls = false;//不捕获对错误线程的调用
this.CmdStar.Enabled = false;
this.CmdStop.Enabled = true;
this.StateMsg.Text = "服务正在运行..." + " 运行端口:6888";
this.ClientList.Items.Add("服务于 " + DateTime.Now.ToString() + " 开始运行.");
}
//接受客户端连接的方法
private void RecieveAccept()
{
int recv;
byte[] revData = new byte[1024];
byte[] sendData = new byte[1024];
//得到客户机IP
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(this.RemoteIp.Text), Convert.ToInt32(RemotePort.Text));
EndPoint Remote = ipep;
recv = ServerSocket.ReceiveFrom(revData, ref Remote);
receiveMsg.Items.Add("我是服务端,客户端连接成功");
receiveMsg.Items.Add(Encoding.Unicode.GetString(revData, 0, recv));
//客户机连接成功后,发送欢迎信息
string welcome = "Welcome !";
sendData = Encoding.Unicode.GetBytes(welcome);
ServerSocket.SendTo(sendData, sendData.Length, SocketFlags.None, Remote);
while (true)
{
//接受信息
recv = ServerSocket.ReceiveFrom(revData, ref Remote);
receiveMsg.Items.Add(Encoding.Unicode.GetString(revData, 0, recv));
//发送信息
string recvDateSucceed = string.Format("服务器已收到.");
sendData = Encoding.Unicode.GetBytes(Station_Reporting());
ServerSocket.SendTo(sendData, sendData.Length, SocketFlags.None, Remote);
//设定周期
Thread.Sleep(3000);//阻止设定时间
}
}
private string Station_Reporting()
{
//0002 0001 0001 0002 0014
//进站触发(0x0002),起始站阎村东(0x0001),当前站阎村东(0x0002),下一站紫草坞(0x0014),终点站燕山(0x0014)
string baowen = "00020001000100020014";
return baowen;
}
private void btnSend_Click(object sender, EventArgs e)
{
string msg = sendMsg.Text;
//发送UDP数据包
Byte[] data = Encoding.Unicode.GetBytes(msg);
ServerSocket.SendTo(data, Remote); ;
receiveMsg.Items.Add("来自服务器的消息:" + sendMsg.Text);
}
private void CmdStop_Click(object sender, EventArgs e)
{
ServerThread.Abort();//线程终止
ServerSocket.Close();//关闭socket
this.CmdStar.Enabled = true;
this.CmdStop.Enabled = false;
this.StateMsg.Text = "等待运行...";
this.ClientList.Items.Add("服务于 " + DateTime.Now.ToString() + " 停止运行.");
}
private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
{
ServerThread.Abort();//线程终止
ServerSocket.Close();//关闭SOCKET
Application.Exit();
}
private void label5_Click(object sender, EventArgs e)
{
}
}
}