本人是做嵌入式开发的,上位机只会一点,入门阶段,下面程序是自己做的测试程序一部分
1. 包含空间
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;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
2. 新建socket
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "connect")
{
try
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.Bind(new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text)));
//t = new Thread(sendMsg);
t2 = new Thread(ReciveMsg);
t2.Start();
buttonen(true);
button1.Text = "disconnect";
}
catch
{
MessageBox.Show("connect message is error", "错误");//出错提示
}
}
else
{
t2.Abort();
client.Close();
button1.Text = "connect";
buttonen(false);
}
3.发送数据
private void button2_Click(object sender, EventArgs e)
{
byte[] Data = new byte[((sendBox1.Text.Length) / 2)+36];//作用同上集
//EndPoint point = new IPEndPoint(IPAddress.Parse("192.168.3.29"), 16800);
EndPoint point = new IPEndPoint(IPAddress.Parse(sendboxip.Text), int.Parse(sendport.Text));
if (radioButton2.Checked) //字符模式
{
try
{
string msg = sendBox1.Text;
client.SendTo(Encoding.Default.GetBytes(msg), point);
}
catch
{
MessageBox.Show("send message is error", "错误");//出错提示
}
}
else
{
try
{
if (0 == (sendBox1.Text.Length) % 2)
{
for (int i = 0; i < (sendBox1.Text.Length) / 2; i++)
{
Data[i] = Convert.ToByte(sendBox1.Text.Substring(i * 2, 2), 16);
// client.SendTo(Data, point);
}
client.SendTo(Data, point);
// client.Send(Data, 0);
}
else
MessageBox.Show("send message len is error", "错误");//出错提示
}
catch
{
MessageBox.Show("send message is error", "错误");//出错提示
}
}
}
3.接收udp数据
void ReciveMsg()
{
while (true)
{
EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
byte[] buffer = new byte[2048];
int length = client.ReceiveFrom(buffer, ref point);//接收数据报
recv = "";
recv += Encoding.UTF8.GetString(buffer, 0, length);
//recv += "\r\n";
if(length > 0)
{
if (radioButton3.Checked) //字符形似
{
AddContent(recv, richTextBox1);
AddContentline(richTextBox1);
}
else
{
for (int i = 0; i < length; i++)
{
string str = Convert.ToString(buffer[i], 16).ToUpper();//转换为大写十六进制字符串
AddContent(str, richTextBox1);
//textBox1.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + " ");//空位补“0”
}
AddContentline(richTextBox1);
}
}
//txtReciv.Text += recv;
}
}