【发布时间】:2018-08-10 12:00:59
【问题描述】:
我知道这个论坛上已经有很多查询。我已经搜索过了,最后我被困在这个问题上,这就是我问它的原因。 我有许多可以在 UDP 上通信的设备。 我想查询他们的状态更新。这是我的代码。
List<IPAddress> iPAdd = new List<IPAddress>();
foreach (string s in ipaddress)
{
IPAddress ips = IPAddress.Parse(s);
iPAdd.Add(ips);
}
//The main socket on which the server listens to the clients
byte[] byteData = new byte[1024];
Byte[] dataToSend = new Byte[] { 0x8B, 0xB9, 0x00, 0x03, 0x05, 0x01, 0x09 };
try
{
serverSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
//Assign the any IP of the machine and listen on port number 1200
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
//Bind this address to the server
serverSocket.Bind(ipEndPoint);
foreach(IPAddress ip in iPAdd)
{
IPEndPoint ipe = new IPEndPoint(ip, 1024);
EndPoint e = (EndPoint)ipe;
eps.Add(e);
}
//Start sending data
foreach(EndPoint ep in eps)
{
serverSocket.BeginSendTo(dataToSend, 0, dataToSend.Length, SocketFlags.None, ep,
new AsyncCallback(OnSend), ep);
Thread.Sleep(50);
Receive(ep);
}
}
catch (Exception ex)
{
string mess = ex.Message;
}
接收方式-
private void Receive(EndPoint ep)
{
Byte[] receiveBytes = new Byte[1024];
IPEndPoint localip = new IPEndPoint(IPAddress.Any, 1200);
UdpClient receivingUdpClient = new UdpClient(localip);
receivingUdpClient.Client.Receive(receiveBytes);
receivingUdpClient.Dispose();
}
我通过接收UdpClient 收到的错误是 -
“发送或接收数据的请求被禁止,因为套接字未连接并且(当使用 sendto 调用在数据报套接字上发送时)没有提供地址”
我做错了什么。?如果我完全错了,那么也..欢迎任何建议和建议
【问题讨论】:
-
UDP 有两种类型 1) 广播 2) 非广播。要允许多个套接字接收/发送,您必须使用广播。非广播与 TCP 相同(仅允许一对一),只是没有数据确认。确认使 TCP 比 UDP 更可靠。
-
感谢 jdweng.. 我现在将进行更改并以这种方式进行测试.. 并让您知道输出
-
我改变了 2 或 3 种方法来实现这一点。这是我今天的最终代码..但我也被困在这里。
-
刷新网页时出错 - 通常每个套接字地址(协议/网络地址/端口)只允许使用一次 ....
-
您是否尝试在同一台 PC 上测试多个客户端?在实际情况下,每个客户端都有自己的 IP。在同一台 PC 上测试时,客户端都具有相同的 IP。要进行模拟,您需要为每个连接使用不同的端口号。您只能有一个连接具有相同的三个参数 1) 源 IP 2) 目标 IP 3) 端口号。