在改编了一些多播教程后,我改变了发送数据包的方法。
就我而言,我创建了一个大小为 的数据包队列bytes[1024]
,然后通过Socket.Send()
所有在线网络适配器发送
问题:
发送时,调用的另一个方法receiveMessage()
在单独的线程上运行。使用Socket.Bind()
,它捕获数据包,但仅捕获 1 个数据包。
我是否做了太多处理从而延迟(并丢失)收到的数据包?
更新
我正在考虑为传入的数据包添加一个队列,因此 1 个线程捕获并存储,第二个线程处理数据包。
发送方法
Socket _listener_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
foreach (IPAddress localIP in Dns.GetHostAddresses(Dns.GetHostName()).Where(i => i.AddressFamily == AddressFamily.InterNetwork))
{
//handle image and files
_listener_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(_MultiIP, localIP));
_listener_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 1);
_listener_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_listener_socket.MulticastLoopback = true;
_listener_socket.Connect(new IPEndPoint(_MultiIP, _PORT));
int count = MSGS_TO_SEND.Count;
while (count > 0)
{
count--;
byte[] temp = (byte[])(MSGS_TO_SEND.Dequeue());
_listener_socket.Send(temp, _BYTE_BUFFER_SIZE, SocketFlags.None);
MSGS_TO_SEND.Enqueue(temp);
}
//----------------------------------------------
//-------------------SEND DATA------------------
//----------------------------------------------
}
_listener_socket.Close();
接收方式
//initialise multicast group and bind to interface
Socket _sender_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, _PORT);
_sender_socket.Bind(ipep);
IPAddress localip = _MultiIP;
_sender_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(localip, IPAddress.Any));
//{
while (_sender_socket.IsBound && !bStop)
{
byte[] b = new byte[_BYTE_BUFFER_SIZE];
_sender_socket.Receive(b);
char[] chars = new char[_BYTE_BUFFER_SIZE];
System.Buffer.BlockCopy(b, 0, chars, 0, b.Length);
string _message = new string(chars).Trim();
string ip = _message.Substring(0, _message.IndexOf("~"));
_message = _message.Remove(0, _message.IndexOf("~") + 1);
string _flag = _message.Substring(0, _message.IndexOf("~"));
_message = _message.Remove(0, _message.IndexOf("~") + 1);
_message = _message.Replace("\0", string.Empty);
ip = "1.0";
icount++;
handleData(ip, _flag, _message);
}