这是我的问题;我正在尝试制作一个 UDP 服务器 - 客户端交互作为测试。我希望客户端向服务器发送数据,如果服务器与服务器保存的数据匹配,它会发送回复。很简单,对吧?这是一些代码:
客户端发送/接收代码:
void TestUDP()
{
Socket sock_addr = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint srver_endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 36);
string numbers = "1.2.3.4";
byte[] srver_req = Encoding.UTF8.GetBytes("TEST|" + numbers);
sock_addr.SendTo(srver_req, srver_endpoint);
EndPoint ref_endpoint = (EndPoint)srver_endpoint;
byte[] req_reply = new byte[1000];
sock_addr.ReceiveFrom(req_reply, ref ref_endpoint);
string reply = Encoding.UTF8.GetString(req_reply).Trim();
string[] s_str = reply.Split('|');
if (s_str[0] == "HEY")
{
MessageBox.Show("HEY");
}
else
{
MessageBox.Show("NO");
}
}
现在一些服务器代码:
public void start()
{
udp_sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udp_sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
udp_thr = new Thread(udpListen);
udp_thr.Start();
}
void udpListen()
{
byte[] data = new byte[1024];
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 36);
udp_sock.Bind(ip);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
while (true)
{
udp_sock.ReceiveFrom(data, ref Remote);
Parse(data, Remote);
}
}
void Parse(byte[] data, EndPoint Remote)
{
string decData = Encoding.UTF8.GetString(data).Trim();
string[] s_str = decData.Split('|');
byte[] sendBuffer = new byte[] { };
switch (s_str[0])
{
case "TEST":
string data1 = s_str[1];
if (data1 == "1.2.3.4")
{
sendBuffer = Encoding.UTF8.GetBytes("HEY|");
}
else if(data1 != "1.2.3.4")
{
sendBuffer = Encoding.UTF8.GetBytes("NO|");
}
udp_sock.SendTo(sendBuffer, Remote);
break;
}
}
现在的问题是,它总是说“不”,我不知道为什么。对我来说,这看起来应该可行,我做错了什么?我已经把这个套接字放到了广播上,因为我也想用它来处理广播请求。那是问题吗?