[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.Text;
//添加的命名空间引用
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text.RegularExpressions;
namespace CoreMes.UDP
{
class UDP
{
int remotePort;
string remoteIp;
int ReceviePort;
IPEndPoint remotePoint;
public delegate void ReceiverDataDel(string message);
public event ReceiverDataDel ReceiverdataEvent;
/// <summary>
/// 初始化
/// </summary>
/// <param name="remoteip">远程主机ip</param>
/// <param name="remoteP">远程主机端口</param>
/// <param name="port">本地主机端口</param>
public UDP(string remoteip,int remoteP,int port)
{
this.remotePort = remoteP;
this.ReceviePort = port;
Regex ipRe = new Regex(@"2[0-4]\d|25[0-5]|1\d?\d?|[2-99]\.(2[0-4]\d|25[0-5]|0|1\d?\d?|[2-99]\.){2}2[0-4]\d|25[0-5]|0|1\d?\d?|[2-99]");
if(ipRe.IsMatch(remoteip))
{
this.remoteIp = remoteip;
remotePoint = new IPEndPoint(IPAddress.Parse(remoteIp), this.remotePort);
}
else
{
throw new Exception("ip地址格式不对");
}
//本地监听端口
Thread receiverThread = new Thread(this.ReceiveData);
receiverThread.IsBackground = true;
receiverThread.Start();
}
/// <summary>
/// 在后台运行的接收线程
/// </summary>
private void ReceiveData()
{
//在本机指定的端口接收
UdpClient udpClient = new UdpClient(ReceviePort);
IPEndPoint remote = null;
//接收从远程主机发送过来的信息;
while (true)
{
try
{
//关闭udpClient时此句会产生异常
byte[] bytes = udpClient.Receive(ref remote);
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
//消息处理
if(ReceiverdataEvent!=null)
{
ReceiverdataEvent(remote.ToString()+":"+str);
}
}
catch(Exception ex)
{
throw ex;
}
}
}
/// <summary>
/// 发送数据到远程主机
/// </summary>
public void SendData(string message)
{
UdpClient myUdpClient = new UdpClient();
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);
try
{
myUdpClient.Send(bytes, bytes.Length, remotePoint);
myUdpClient.Close();
}
catch (Exception err)
{
throw err;
}
finally
{
myUdpClient.Close();
}
}
}
}
|