C#利用UDP协议实现多IP数据采集并储存
答案:1 悬赏:80 手机版
解决时间 2021-04-06 20:21
- 提问者网友:却不属于对方
- 2021-04-06 11:05
给个例子或者源码,要C#的其他语言的就算了,我就这点分了
最佳答案
- 五星知识达人网友:西岸风
- 2021-04-06 11:27
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using log4net;
namespace NetSockApi
{
public class Udp
{
private static readonly ILog log = LogManager.GetLogger(typeof(Udp));
private Socket socket;
//private int localPort = 0;
private long bufferSize = 0;
//private short ttl = 0;
private byte[] buffer =null;
private EndPoint _localEndPoint;
private EndPoint _remoteEndPoint;
private IPAddress _groupAddr;
private int _groupPort = 0;
//private EolFormat _eofFormat = EolFormat.EOL_LFCR;
LinkedList<DataPacket> _readBuffer;
public Udp()
{
this.bufferSize = 1024; //default buffer size
buffer = new byte[bufferSize];
//this.ttl = 0;
_readBuffer = new LinkedList<DataPacket>();
}
~Udp()
{
Disconnect();
_readBuffer.Clear();
}
public bool Create(int bufferSize)
{
try
{
this.bufferSize = bufferSize;
this.buffer = new byte[this.bufferSize];
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
return false;
}
}
public bool Connect(string remoteAddr, int remotePort)
{
try
{
this._groupAddr = IPAddress.Parse(remoteAddr);
this._groupPort = remotePort;
_localEndPoint = new IPEndPoint(IPAddress.Any, _groupPort) as EndPoint;
_remoteEndPoint = new IPEndPoint(_groupAddr, _groupPort) as EndPoint;
//init Socket properties:
socket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.NoDelay, 1);
//allow for loopback testing
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
//extremly important to bind the Socket before joining multicast groups
socket.Bind(_localEndPoint);
//set multicast flags, sending flags - TimeToLive (TTL)
// 0 - LAN
// 1 - Single Router Hop
// 2 - Two Router Hops...
//socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 0);
//join multicast group
//socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_groupAddr));
//get in waiting mode for data -always (this doesn't halt code execution)
Recieve();
////socket.BeginReceiveFrom(buffer, 0, buffer.Length,
//// SocketFlags.None, ref this._remoteEndPoint, new AsyncCallback(OnReceive), _remoteEndPoint);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
return false;
}
}
////public bool Connect(string groupAddr, int groupPort)
////{
//// try
//// {
//// _groupAddr = IPAddress.Parse(groupAddr);
//// _groupPort = groupPort;
//// _remoteEndPoint = new IPEndPoint(_groupAddr, _groupPort) as EndPoint; //should be set 0
//// socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//// MulticastOption multicastOption = new MulticastOption(IPAddress.Parse(groupAddr));
//// socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOption);
//// socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, 1);
//// socket.Ttl = 5;
//// socket.BeginReceiveFrom(buffer, 0, buffer.Length,
//// SocketFlags.None, ref this._remoteEndPoint, new AsyncCallback(OnReceive), _remoteEndPoint);
//// return true;
//// }
//// catch (Exception ex)
//// {
//// return false;
//// }
////}
void Disconnect()
{
socket.Close();
}
public bool Accept(string groupAddr, int groupPort)
{
try
{
this._groupAddr = IPAddress.Parse(groupAddr);
this._groupPort = groupPort;
_localEndPoint = new IPEndPoint(IPAddress.Any, _groupPort) as EndPoint;
_remoteEndPoint = new IPEndPoint(_groupAddr, _groupPort) as EndPoint;
//init Socket properties:
socket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.NoDelay, 1);
//allow for loopback testing
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
//extremly important to bind the Socket before joining multicast groups
socket.Bind(_localEndPoint);
//set multicast flags, sending flags - TimeToLive (TTL)
// 0 - LAN
// 1 - Single Router Hop
// 2 - Two Router Hops...
//socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 0);
//join multicast group
//socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_groupAddr));
//get in waiting mode for data -always (this doesn't halt code execution)
Recieve();
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
return false;
}
}
//initial receive function - called only once
private void Recieve()
{
try
{
// Create the state object.
StateObject state = new StateObject(socket, this.bufferSize);
state.workSocket = socket;
//
// Begin receiving the data from the remote device.
socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref _localEndPoint,
new AsyncCallback(OnReceive), state);
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
}
protected virtual void HandleIncomingDataEvent()
{
//Do Nothing
}
private void ProcessIncomingData(byte[] data,EndPoint remoteEndPoint)
{
DataPacket tmpDp = new DataPacket();
tmpDp.buf = new byte[data.Length];
tmpDp.len = data.Length;
tmpDp.pos = 0;
data.CopyTo(tmpDp.buf, 0);
_readBuffer.AddLast(tmpDp);
}
private void OnReceive(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the async state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
//EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0) as EndPoint;
client.EndReceiveFrom(ar, ref _localEndPoint);
ProcessIncomingData(state.Buffer, _localEndPoint);
HandleIncomingDataEvent();
Array.Clear(state.Buffer,0,(int)this.bufferSize); //clean 0
client.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length,
SocketFlags.None, ref this._localEndPoint, new AsyncCallback(OnReceive), state);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
// throw (ex);
}
}
public string ReadString()
{
byte[] buffer = new byte[4096];
int byteReads = 0;
byteReads = Read(ref buffer, 4096);
ASCIIEncoding encoding = new ASCIIEncoding();
return encoding.GetString(buffer);
}
public int Read(ref byte[] buf, int len)
{
int readBytes = 0;
DataPacket tmpSwap;
DataPacket data = new DataPacket();
if(len <= 0) return 0;
if(_readBuffer.Count > 0)
{
tmpSwap = _readBuffer.First.Value;
data.buf = new byte [tmpSwap.len];
tmpSwap.buf.CopyTo(data.buf, 0);
data.len = tmpSwap.len;
data.pos = 0;
_readBuffer.RemoveFirst();
}
if(len > data.len)
readBytes = data.len;
else
readBytes = len;
data.buf.CopyTo(buf, 0);
return readBytes;
}
public void Send(byte[] data)
{
try
{
//EndPoint localEndPoint = new IPEndPoint(IPAddress.Any, localPort) as EndPoint;
socket.BeginSendTo(data, 0, data.Length,
SocketFlags.None, _remoteEndPoint, new AsyncCallback(OnSend), _remoteEndPoint);
}
catch (Exception ex)
{
log.Error(ex.Message);
}
}
public void Send(byte[] data, int len)
{
try
{
//EndPoint localEndPoint = new IPEndPoint(IPAddress.Any, localPort) as EndPoint;
socket.BeginSendTo(data, 0, len,
SocketFlags.None, _remoteEndPoint, new AsyncCallback(OnSend), _remoteEndPoint);
}
catch (Exception ex)
{
log.Error(ex.Message);
}
}
public void Send(string strMessage)
{
byte[] bytesToSend = Encoding.ASCII.GetBytes(strMessage);
if (bytesToSend != null && bytesToSend.Length > 0)
Send(bytesToSend);
}
//no test it
public void SendLine(string strLine)
{
byte[] bytesToSend = Encoding.ASCII.GetBytes(strLine);
byte[] buf = new byte[bytesToSend.Length + 2];
bytesToSend.CopyTo(buf, 0);
buf[bytesToSend.Length] = (Byte)'\r';
buf[bytesToSend.Length + 1] = (Byte)'\n';
Send(buf);
}
private void OnSend(IAsyncResult ar)
{
try
{
socket.EndSend(ar);
}
catch (Exception ex)
{
MessageBox.Show("不能发送到: " + _groupAddr.ToString());
}
}
}
}
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using log4net;
namespace NetSockApi
{
public class Udp
{
private static readonly ILog log = LogManager.GetLogger(typeof(Udp));
private Socket socket;
//private int localPort = 0;
private long bufferSize = 0;
//private short ttl = 0;
private byte[] buffer =null;
private EndPoint _localEndPoint;
private EndPoint _remoteEndPoint;
private IPAddress _groupAddr;
private int _groupPort = 0;
//private EolFormat _eofFormat = EolFormat.EOL_LFCR;
LinkedList<DataPacket> _readBuffer;
public Udp()
{
this.bufferSize = 1024; //default buffer size
buffer = new byte[bufferSize];
//this.ttl = 0;
_readBuffer = new LinkedList<DataPacket>();
}
~Udp()
{
Disconnect();
_readBuffer.Clear();
}
public bool Create(int bufferSize)
{
try
{
this.bufferSize = bufferSize;
this.buffer = new byte[this.bufferSize];
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
return false;
}
}
public bool Connect(string remoteAddr, int remotePort)
{
try
{
this._groupAddr = IPAddress.Parse(remoteAddr);
this._groupPort = remotePort;
_localEndPoint = new IPEndPoint(IPAddress.Any, _groupPort) as EndPoint;
_remoteEndPoint = new IPEndPoint(_groupAddr, _groupPort) as EndPoint;
//init Socket properties:
socket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.NoDelay, 1);
//allow for loopback testing
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
//extremly important to bind the Socket before joining multicast groups
socket.Bind(_localEndPoint);
//set multicast flags, sending flags - TimeToLive (TTL)
// 0 - LAN
// 1 - Single Router Hop
// 2 - Two Router Hops...
//socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 0);
//join multicast group
//socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_groupAddr));
//get in waiting mode for data -always (this doesn't halt code execution)
Recieve();
////socket.BeginReceiveFrom(buffer, 0, buffer.Length,
//// SocketFlags.None, ref this._remoteEndPoint, new AsyncCallback(OnReceive), _remoteEndPoint);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
return false;
}
}
////public bool Connect(string groupAddr, int groupPort)
////{
//// try
//// {
//// _groupAddr = IPAddress.Parse(groupAddr);
//// _groupPort = groupPort;
//// _remoteEndPoint = new IPEndPoint(_groupAddr, _groupPort) as EndPoint; //should be set 0
//// socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//// MulticastOption multicastOption = new MulticastOption(IPAddress.Parse(groupAddr));
//// socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOption);
//// socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, 1);
//// socket.Ttl = 5;
//// socket.BeginReceiveFrom(buffer, 0, buffer.Length,
//// SocketFlags.None, ref this._remoteEndPoint, new AsyncCallback(OnReceive), _remoteEndPoint);
//// return true;
//// }
//// catch (Exception ex)
//// {
//// return false;
//// }
////}
void Disconnect()
{
socket.Close();
}
public bool Accept(string groupAddr, int groupPort)
{
try
{
this._groupAddr = IPAddress.Parse(groupAddr);
this._groupPort = groupPort;
_localEndPoint = new IPEndPoint(IPAddress.Any, _groupPort) as EndPoint;
_remoteEndPoint = new IPEndPoint(_groupAddr, _groupPort) as EndPoint;
//init Socket properties:
socket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.NoDelay, 1);
//allow for loopback testing
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
//extremly important to bind the Socket before joining multicast groups
socket.Bind(_localEndPoint);
//set multicast flags, sending flags - TimeToLive (TTL)
// 0 - LAN
// 1 - Single Router Hop
// 2 - Two Router Hops...
//socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 0);
//join multicast group
//socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_groupAddr));
//get in waiting mode for data -always (this doesn't halt code execution)
Recieve();
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
return false;
}
}
//initial receive function - called only once
private void Recieve()
{
try
{
// Create the state object.
StateObject state = new StateObject(socket, this.bufferSize);
state.workSocket = socket;
//
// Begin receiving the data from the remote device.
socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref _localEndPoint,
new AsyncCallback(OnReceive), state);
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
}
protected virtual void HandleIncomingDataEvent()
{
//Do Nothing
}
private void ProcessIncomingData(byte[] data,EndPoint remoteEndPoint)
{
DataPacket tmpDp = new DataPacket();
tmpDp.buf = new byte[data.Length];
tmpDp.len = data.Length;
tmpDp.pos = 0;
data.CopyTo(tmpDp.buf, 0);
_readBuffer.AddLast(tmpDp);
}
private void OnReceive(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the async state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
//EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0) as EndPoint;
client.EndReceiveFrom(ar, ref _localEndPoint);
ProcessIncomingData(state.Buffer, _localEndPoint);
HandleIncomingDataEvent();
Array.Clear(state.Buffer,0,(int)this.bufferSize); //clean 0
client.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length,
SocketFlags.None, ref this._localEndPoint, new AsyncCallback(OnReceive), state);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
// throw (ex);
}
}
public string ReadString()
{
byte[] buffer = new byte[4096];
int byteReads = 0;
byteReads = Read(ref buffer, 4096);
ASCIIEncoding encoding = new ASCIIEncoding();
return encoding.GetString(buffer);
}
public int Read(ref byte[] buf, int len)
{
int readBytes = 0;
DataPacket tmpSwap;
DataPacket data = new DataPacket();
if(len <= 0) return 0;
if(_readBuffer.Count > 0)
{
tmpSwap = _readBuffer.First.Value;
data.buf = new byte [tmpSwap.len];
tmpSwap.buf.CopyTo(data.buf, 0);
data.len = tmpSwap.len;
data.pos = 0;
_readBuffer.RemoveFirst();
}
if(len > data.len)
readBytes = data.len;
else
readBytes = len;
data.buf.CopyTo(buf, 0);
return readBytes;
}
public void Send(byte[] data)
{
try
{
//EndPoint localEndPoint = new IPEndPoint(IPAddress.Any, localPort) as EndPoint;
socket.BeginSendTo(data, 0, data.Length,
SocketFlags.None, _remoteEndPoint, new AsyncCallback(OnSend), _remoteEndPoint);
}
catch (Exception ex)
{
log.Error(ex.Message);
}
}
public void Send(byte[] data, int len)
{
try
{
//EndPoint localEndPoint = new IPEndPoint(IPAddress.Any, localPort) as EndPoint;
socket.BeginSendTo(data, 0, len,
SocketFlags.None, _remoteEndPoint, new AsyncCallback(OnSend), _remoteEndPoint);
}
catch (Exception ex)
{
log.Error(ex.Message);
}
}
public void Send(string strMessage)
{
byte[] bytesToSend = Encoding.ASCII.GetBytes(strMessage);
if (bytesToSend != null && bytesToSend.Length > 0)
Send(bytesToSend);
}
//no test it
public void SendLine(string strLine)
{
byte[] bytesToSend = Encoding.ASCII.GetBytes(strLine);
byte[] buf = new byte[bytesToSend.Length + 2];
bytesToSend.CopyTo(buf, 0);
buf[bytesToSend.Length] = (Byte)'\r';
buf[bytesToSend.Length + 1] = (Byte)'\n';
Send(buf);
}
private void OnSend(IAsyncResult ar)
{
try
{
socket.EndSend(ar);
}
catch (Exception ex)
{
MessageBox.Show("不能发送到: " + _groupAddr.ToString());
}
}
}
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯