【文件属性】:
文件名称:udp 和tcp结合视频监控系统.zip
文件大小:6.05MB
文件格式:ZIP
更新时间:2023-01-31 01:14:13
udp分包,udp组包,UDP收
using System;
using System.Collections.Concurrent;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Gimela.Net.Sockets
{
///
/// UDP发送器
///
public class UdpSender : IDisposable
{
private bool disposed = false;
private Thread senderThread;
private UdpClient udpClient;
private ConcurrentQueue queue;
private readonly ManualResetEvent waiter;
///
/// UDP发送器
///
/// 发送目的地址
/// 发送目的端口
public UdpSender(string sentToAddress, int sentToPort)
{
Address = sentToAddress;
Port = sentToPort;
this.Encoding = Encoding.Default;
queue = new ConcurrentQueue();
waiter = new ManualResetEvent(false);
udpClient = new UdpClient();
udpClient.AllowNatTraversal(true);
senderThread = new Thread(new ThreadStart(WorkThread));
}
///
/// 发送目的地址
///
public string Address { get; private set; }
///
/// 发送目的端口
///
public int Port { get; private set; }
///
/// 发送器是否正在运行
///
public bool IsRunning { get; private set; }
///
/// 发送器所使用的编码
///
public Encoding Encoding { get; set; }
///
/// 启动发送器
///
/// UDP发送器
public UdpSender Start()
{
if (!IsRunning)
{
IsRunning = true;
senderThread.Start();
}
return this;
}
///
/// 停止发送器
///
/// UDP发送器
public UdpSender Stop()
{
IsRunning = false;
return this;
}
///
/// 发送数据报文
///
/// 数据报文
/// UDP发送器
public UdpSender Send(byte[] datagram)
{
if (!IsRunning)
throw new InvalidProgramException("This sender has not been started.");
queue.Enqueue(datagram);
waiter.Set();
return this;
}
///
/// 发送数据报文
///
/// 数据报文
/// UDP发送器
public UdpSender Send(string datagram)
{
if (!IsRunning)
throw new InvalidProgramException("This sender has not been started.");
queue.Enqueue(this.Encoding.GetBytes(datagram));
waiter.Set();
return this;
}
private void WorkThread()
{
while (IsRunning)
{
waiter.WaitOne();
waiter.Reset();
while (queue.Count > 0)
{
byte[] datagram = null;
if (queue.TryDequeue(out datagram))
{
udpClient.BeginSend(datagram, datagram.Length, Address, Port, SendCompleted, udpClient);
}
}
}
}
private void SendCompleted(IAsyncResult ar)
{
UdpClient udp = ar.AsyncState as UdpClient;
if (udp != null)
{
udp.EndSend(ar);
}
}
#region IDisposable Members
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
/// Releases unmanaged and - optionally - managed resources
///
/// true to release both managed and unmanaged resources; false to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
Stop();
waiter.Close();
if (senderThread != null)
{
try
{
senderThread.Abort();
}
catch (ThreadStateException) { }
finally
{
senderThread = null;
}
}
if (udpClient != null)
{
udpClient.Close();
udpClient = null;
}
}
disposed = true;
}
}
#endregion
}
}