实例介绍
【实例简介】
c#基于UDP的通信调试软件,支持16进制发送与接收
【实例截图】
【核心代码】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UDPtiaoshi
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;//允许跨线程
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;//允许跨线程
}
private IPEndPoint ipLocalPoint;
private EndPoint RemotePoint;
private Socket mySocket;
private bool RunningFlag = false;
private Thread thread;
// 获得本机局域网IP地址
private string getIPAddress()
{
IPAddress[] AddressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
if (AddressList.Length < 1)
{
return "";
}
return AddressList[0].ToString();
}
//使窗口载入时显示本机地址
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = getIPAddress();
}
private IPEndPoint ipLocalPoint;
private EndPoint RemotePoint;
private Socket mySocket;
private bool RunningFlag = false;
private Thread thread;
// 获得本机局域网IP地址
private string getIPAddress()
{
IPAddress[] AddressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
if (AddressList.Length < 1)
{
return "";
}
return AddressList[0].ToString();
}
//使窗口载入时显示本机地址
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = getIPAddress();
}
private IPAddress getValidIP(string ip)
{
IPAddress lip = null;
//测试IP是否有效
try
{
//是否为空
if (!IPAddress.TryParse(ip, out lip))
{
throw new ArgumentException(
"IP无效,不能启动DUP");
}
}
catch (Exception e)
{
//ArgumentException,
//FormatException,
//OverflowException
Console.WriteLine("无效的IP:" e.ToString());
this.textBox5.AppendText("无效的IP:" e.ToString() "\n");
return null;
}
return lip;
}
//连接按钮
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "连接")
{
try
{
Cip = getValidIP(textBox3.Text);
Cport = getValidPort(textBox4.Text);
IPEndPoint ipep = new IPEndPoint(Cip, Cport);
RemotePoint = (EndPoint)(ipep);
//得到本机IP,设置UDP端口号,用于绑定网络地址
ip = getValidIP(textBox1.Text);
port = getValidPort(textBox2.Text);
ipLocalPoint = new IPEndPoint(ip, port);
//定义网络类型,数据连接类型和网络协议UDP
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//绑定网络地址
mySocket.Bind(ipLocalPoint); //用指定端口发送数据
RunningFlag = true;
thread = new Thread(new ThreadStart(this.ReceiveHandle));
thread.Start();
button1.Text = "断开";
}
catch
{
MessageBox.Show("请重新选择端口号");
}
{
IPAddress lip = null;
//测试IP是否有效
try
{
//是否为空
if (!IPAddress.TryParse(ip, out lip))
{
throw new ArgumentException(
"IP无效,不能启动DUP");
}
}
catch (Exception e)
{
//ArgumentException,
//FormatException,
//OverflowException
Console.WriteLine("无效的IP:" e.ToString());
this.textBox5.AppendText("无效的IP:" e.ToString() "\n");
return null;
}
return lip;
}
//连接按钮
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "连接")
{
try
{
Cip = getValidIP(textBox3.Text);
Cport = getValidPort(textBox4.Text);
IPEndPoint ipep = new IPEndPoint(Cip, Cport);
RemotePoint = (EndPoint)(ipep);
//得到本机IP,设置UDP端口号,用于绑定网络地址
ip = getValidIP(textBox1.Text);
port = getValidPort(textBox2.Text);
ipLocalPoint = new IPEndPoint(ip, port);
//定义网络类型,数据连接类型和网络协议UDP
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//绑定网络地址
mySocket.Bind(ipLocalPoint); //用指定端口发送数据
RunningFlag = true;
thread = new Thread(new ThreadStart(this.ReceiveHandle));
thread.Start();
button1.Text = "断开";
}
catch
{
MessageBox.Show("请重新选择端口号");
}
}
else
{
else
{
mySocket.Close();
RunningFlag = false;
thread.Abort();
button1.Text = "连接";
}
RunningFlag = false;
thread.Abort();
button1.Text = "连接";
}
}
//定义一个委托
public delegate void MyInvoke(string strRecv);
private void ReceiveHandle()
{
//接收数据处理线程
string msg;
byte[] data = new byte[1024];
MyInvoke myI = new MyInvoke(UpdateMsgTextBox);
while (RunningFlag)
{
try
{
//定义一个委托
public delegate void MyInvoke(string strRecv);
private void ReceiveHandle()
{
//接收数据处理线程
string msg;
byte[] data = new byte[1024];
MyInvoke myI = new MyInvoke(UpdateMsgTextBox);
while (RunningFlag)
{
try
{
if (mySocket == null || mySocket.Available < 1)
{
//Thread.Sleep(2000);
continue;
}
//跨线程调用控件
//接收UDP数据报,引用参数RemotePoint获得源地址
int rlen = mySocket.ReceiveFrom(data, ref RemotePoint);
{
//Thread.Sleep(2000);
continue;
}
//跨线程调用控件
//接收UDP数据报,引用参数RemotePoint获得源地址
int rlen = mySocket.ReceiveFrom(data, ref RemotePoint);
msg = Encoding.Default.GetString(data, 0, rlen);
textBox3.Text = RemotePoint.ToString().Substring(0, RemotePoint.ToString().IndexOf(":"));
textBox4.Text = RemotePoint.ToString().Substring(RemotePoint.ToString().IndexOf(":") 1);
if (checkBox1.Checked == true)
{
byte[] byteThird = data;
string message = "";
//ASCzhuan 16jinzhi 多余的加0补齐
for (int i = 0; i < rlen; i )
{
if (byteThird[i].ToString("X2").Length == 1)
message = "0" byteThird[i].ToString("X2");
else
message = byteThird[i].ToString("X2");
}
//将接收到的十六进制数据两个一组加空格
string t = message;
string result = Regex.Replace(t, @".{2}", "$0 ");
textBox5.Text = result;
}
else
{
textBox5.BeginInvoke(myI, new object[] { RemotePoint.ToString() " : " msg });
}
}
catch
// catch (Exception e)
{
//MessageBox.Show(e.ToString());
}
}
}
//接收数据显示
private void UpdateMsgTextBox(string msg)
{
textBox4.Text = RemotePoint.ToString().Substring(RemotePoint.ToString().IndexOf(":") 1);
if (checkBox1.Checked == true)
{
byte[] byteThird = data;
string message = "";
//ASCzhuan 16jinzhi 多余的加0补齐
for (int i = 0; i < rlen; i )
{
if (byteThird[i].ToString("X2").Length == 1)
message = "0" byteThird[i].ToString("X2");
else
message = byteThird[i].ToString("X2");
}
//将接收到的十六进制数据两个一组加空格
string t = message;
string result = Regex.Replace(t, @".{2}", "$0 ");
textBox5.Text = result;
}
else
{
textBox5.BeginInvoke(myI, new object[] { RemotePoint.ToString() " : " msg });
}
}
catch
// catch (Exception e)
{
//MessageBox.Show(e.ToString());
}
}
}
//接收数据显示
private void UpdateMsgTextBox(string msg)
{
this.textBox5.AppendText(msg "\n");
}
//测试端口号是否有效
private int getValidPort(string port)
{
int lport;
try
{
//是否为空
if (port == "")
{
throw new ArgumentException(
"端口号无效,不能启动DUP");
}
lport = System.Convert.ToInt32(port);
}
catch (Exception e)
{
//ArgumentException,
//FormatException,
//OverflowException
Console.WriteLine("无效的端口号:" e.ToString());
this.textBox5.AppendText("无效的端口号:" e.ToString() "\n");
return -1;
}
return lport;
}
private void button5_Click(object sender, EventArgs e)
{
if (button1.Text == "连接")
{
MessageBox.Show("请打开连接");
}
else
{
//得到客户机IP
Cip = getValidIP(textBox3.Text);
Cport = getValidPort(textBox4.Text);
IPEndPoint ipep = new IPEndPoint(Cip, Cport);
RemotePoint = (EndPoint)(ipep);
if (checkBox2.Checked == true)
{
string b = textBox6.Text.ToUpper();
string[] d = b.Split(' ');
for (int i = 0; i < d.Length; i )
{
b = d[i];
if (b.Length % 2 != 0)
{
b = b.Substring(0, b.Length - 1) "0" b.Substring(b.Length - 1);
}
byte[] c = HEXstring_to_bytys(b);
mySocket.SendTo(c, c.Length, SocketFlags.None, RemotePoint);
}
}
else
{
string a = textBox6.Text;
//发送UDP数据包
byte[] f = Encoding.Default.GetBytes(a);
mySocket.SendTo(f, f.Length, SocketFlags.None, RemotePoint);
}
}
}
private byte[] HEXstring_to_bytys(string str)
{
String str1 = "0123456789ABCDEF";
char[] hexs = str.ToCharArray();//将字符串转换为字符数组;
byte[] bytes;
bytes = new byte[str.Length / 2];
int n;
for (int i = 0; i < bytes.Length; i )
{
n = str1.IndexOf(hexs[2 * i]) * 16;
n = str1.IndexOf(hexs[2 * i 1]);
bytes[i] = (byte)(n & 0xff);
}
return bytes;
}
//禁止非十六进制的字母写入
public int Cport { get; set; }
public IPAddress Cip { get; set; }
public int port { get; set; }
public IPAddress ip { get; set; }
private void button4_Click(object sender, EventArgs e)
{
textBox6.Text = "";
textBox6.Focus();
}
private void button2_Click(object sender, EventArgs e)
{
textBox5.Text = "";
}
//禁止非十六进制的字母写入
private void textBox6_KeyPress(object sender, KeyPressEventArgs e)
{
if (checkBox2.Checked == true)
{
//if ((e.KeyChar < 'A' || e.KeyChar > 'F') && (e.KeyChar < 'a' || e.KeyChar > 'f') && (e.KeyChar<48||e.KeyChar>57))
if ((e.KeyChar < 65 || e.KeyChar > 70) && (e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar < 97 || e.KeyChar > 102) && e.KeyChar != 8 && e.KeyChar != 32)
{
e.Handled = true;
}
//可以使用删除和空格键
//if (e.KeyChar == 8 && e.KeyChar == 32)
//{
// e.Handled = false;
//}
}
}
//保存数据
private void button3_Click(object sender, EventArgs e)
{
// 利用SaveFileDialog,让用户指定文件的路径名
SaveFileDialog saveDlg = new SaveFileDialog();
saveDlg.Filter = "文本文件|*.txt";
if (saveDlg.ShowDialog() == DialogResult.OK)
{
// 创建文件,将textBox1中的内容保存到文件中
// saveDlg.FileName 是用户指定的文件路径
FileStream fs = File.Open(saveDlg.FileName, FileMode.Create,FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
// 保存textBox5中所有内容(所有行)
foreach (string line in textBox5.Lines)
{
sw.WriteLine(line);
}
//关闭文件
sw.Flush();
sw.Close();
fs.Close();
// 提示用户:文件保存的位置和文件名
MessageBox.Show("文件已成功保存到" saveDlg.FileName);
}
}
//在窗口关闭时
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (mySocket != null)
{
mySocket.Close();
RunningFlag = false;
thread.Abort();
}
}
}
}
}
//测试端口号是否有效
private int getValidPort(string port)
{
int lport;
try
{
//是否为空
if (port == "")
{
throw new ArgumentException(
"端口号无效,不能启动DUP");
}
lport = System.Convert.ToInt32(port);
}
catch (Exception e)
{
//ArgumentException,
//FormatException,
//OverflowException
Console.WriteLine("无效的端口号:" e.ToString());
this.textBox5.AppendText("无效的端口号:" e.ToString() "\n");
return -1;
}
return lport;
}
private void button5_Click(object sender, EventArgs e)
{
if (button1.Text == "连接")
{
MessageBox.Show("请打开连接");
}
else
{
//得到客户机IP
Cip = getValidIP(textBox3.Text);
Cport = getValidPort(textBox4.Text);
IPEndPoint ipep = new IPEndPoint(Cip, Cport);
RemotePoint = (EndPoint)(ipep);
if (checkBox2.Checked == true)
{
string b = textBox6.Text.ToUpper();
string[] d = b.Split(' ');
for (int i = 0; i < d.Length; i )
{
b = d[i];
if (b.Length % 2 != 0)
{
b = b.Substring(0, b.Length - 1) "0" b.Substring(b.Length - 1);
}
byte[] c = HEXstring_to_bytys(b);
mySocket.SendTo(c, c.Length, SocketFlags.None, RemotePoint);
}
}
else
{
string a = textBox6.Text;
//发送UDP数据包
byte[] f = Encoding.Default.GetBytes(a);
mySocket.SendTo(f, f.Length, SocketFlags.None, RemotePoint);
}
}
}
private byte[] HEXstring_to_bytys(string str)
{
String str1 = "0123456789ABCDEF";
char[] hexs = str.ToCharArray();//将字符串转换为字符数组;
byte[] bytes;
bytes = new byte[str.Length / 2];
int n;
for (int i = 0; i < bytes.Length; i )
{
n = str1.IndexOf(hexs[2 * i]) * 16;
n = str1.IndexOf(hexs[2 * i 1]);
bytes[i] = (byte)(n & 0xff);
}
return bytes;
}
//禁止非十六进制的字母写入
public int Cport { get; set; }
public IPAddress Cip { get; set; }
public int port { get; set; }
public IPAddress ip { get; set; }
private void button4_Click(object sender, EventArgs e)
{
textBox6.Text = "";
textBox6.Focus();
}
private void button2_Click(object sender, EventArgs e)
{
textBox5.Text = "";
}
//禁止非十六进制的字母写入
private void textBox6_KeyPress(object sender, KeyPressEventArgs e)
{
if (checkBox2.Checked == true)
{
//if ((e.KeyChar < 'A' || e.KeyChar > 'F') && (e.KeyChar < 'a' || e.KeyChar > 'f') && (e.KeyChar<48||e.KeyChar>57))
if ((e.KeyChar < 65 || e.KeyChar > 70) && (e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar < 97 || e.KeyChar > 102) && e.KeyChar != 8 && e.KeyChar != 32)
{
e.Handled = true;
}
//可以使用删除和空格键
//if (e.KeyChar == 8 && e.KeyChar == 32)
//{
// e.Handled = false;
//}
}
}
//保存数据
private void button3_Click(object sender, EventArgs e)
{
// 利用SaveFileDialog,让用户指定文件的路径名
SaveFileDialog saveDlg = new SaveFileDialog();
saveDlg.Filter = "文本文件|*.txt";
if (saveDlg.ShowDialog() == DialogResult.OK)
{
// 创建文件,将textBox1中的内容保存到文件中
// saveDlg.FileName 是用户指定的文件路径
FileStream fs = File.Open(saveDlg.FileName, FileMode.Create,FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
// 保存textBox5中所有内容(所有行)
foreach (string line in textBox5.Lines)
{
sw.WriteLine(line);
}
//关闭文件
sw.Flush();
sw.Close();
fs.Close();
// 提示用户:文件保存的位置和文件名
MessageBox.Show("文件已成功保存到" saveDlg.FileName);
}
}
//在窗口关闭时
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (mySocket != null)
{
mySocket.Close();
RunningFlag = false;
thread.Abort();
}
}
}
}
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论