最近在使用UDPclient时候总是遇到问题,为了方便后面使用,简单写了一个类,主线程发送 ,新线程接收数据。支持16进制接收以及发送。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace UDP_Client
{
/// <summary>
/// 显示UDP接收到的内容
/// </summary>
/// <param name="msg"></param>
public delegate void ShowRecvMsg(string msg,string msg2);
public class UdpClientClass
{
public ShowRecvMsg showRecvMsg; // 定义委托接收到的内容其他类处理
public bool IsStartUdpRecive;
UdpClient udpRecvClient; //接收CLient
UdpClient udpSendClient; //发送Client
Thread Recvthread;//接收线程
// = new IPEndPoint(IPAddress.Any,0);
IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, 12340);
/// <summary>
///
/// </summary>
/// <param name="Msg">发送内容</param>
/// <param name="RemoteIp">远端IP</param>
/// <param name="RemotePort">远端端口</param>
public void UdpSendMsgFuc(string Msg,string RemoteIp,int RemotePort)
{
IPAddress iPAddress = IPAddress.Parse(RemoteIp);
IPEndPoint remotePoint = new IPEndPoint(iPAddress, RemotePort);
if (udpSendClient != null)
udpSendClient.Close();
udpSendClient = new UdpClient();
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Msg.Trim());
udpSendClient.Send(buffer, buffer.Length, remotePoint);
}
/// <summary>
///
/// </summary>
/// <param name="Msg"></param>
/// <param name="RemoteIp"></param>
/// <param name="RemotePort"></param>
/// <param name="ishex">是否是16进制发送</param>
public void UdpSendMsgFuc(string Msg, string RemoteIp, int RemotePort, bool ishex)
{
IPAddress iPAddress = IPAddress.Parse(RemoteIp);
IPEndPoint remotePoint = new IPEndPoint(iPAddress, RemotePort);
if (udpSendClient != null)
udpSendClient.Close();
udpSendClient = new UdpClient();
if(ishex)
{
byte[] buffer = hexStringToBytes(Msg.Trim());
udpSendClient.Send(buffer, buffer.Length, remotePoint);
}else
{
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Msg.Trim());
udpSendClient.Send(buffer, buffer.Length, remotePoint);
}
}
/// <summary>
/// 开始接收
/// </summary>
public void StartRecvMsg()
{
try
{
if(Recvthread == null)
Recvthread = new Thread(Udp_ReceiveFunction);
IsStartUdpRecive = true;
Recvthread.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
/// <summary>
/// 停止接收
/// </summary>
public void StopRecvMsg()
{
// throw new NotImplementedException();
try
{
if (!Recvthread.IsAlive)
Recvthread.Abort();
IsStartUdpRecive = false;
Recvthread = null;
// Recvthread.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public bool IsHexRecv;
/// <summary>
/// 接收线程
/// </summary>
private void Udp_ReceiveFunction()
{
if(udpRecvClient == null)
udpRecvClient = new UdpClient(iPEndPoint);
while (IsStartUdpRecive)
{
try
{
byte[] recBuffer = udpRecvClient.Receive(ref iPEndPoint);
if (recBuffer != null)
{
if(IsHexRecv)
{
string receive = bytetohexstring(recBuffer);
showRecvMsg(iPEndPoint.ToString(), receive);
}else
{
string receive = System.Text.Encoding.UTF8.GetString(recBuffer);
showRecvMsg(iPEndPoint.ToString(), receive);
}
}
}
catch( Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
/// <summary>
/// 字符串转16进制Byte
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public byte[] hexStringToBytes(String hexString)
{
if (hexString == null || hexString.Equals(""))
{
return null;
}
hexString = hexString.ToUpper().Replace(" ", "");
int length = hexString.Length / 2;
char[] hexChars = hexString.ToCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++)
{
int pos = i * 2;
d[i] = (byte)(charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private byte charToByte(char c)
{
return (byte)"0123456789ABCDEF".IndexOf(c);
}
private string bytetohexstring(byte[] ReceiveBytes)
{
// throw new NotImplementedException();
string struse = "";
if (ReceiveBytes != null)
{
for (int i = 0; i < ReceiveBytes.Length; i++)
{
struse += string.Format("{0:x}", ReceiveBytes[i]);
}
}
return struse;
}
}
}