我正在尝试编写一个接受请求(大小为 18 字节)的控制台应用程序,然后将某些内容(大小为 7 字节)发送回客户端。我这辈子似乎无法让它发挥作用。我可以很好地接收数据,但我发回的数据永远不会到达客户端。
这是我的代码
static void Main(string[] args)
{
// Data to return
byte[] ret = { 0xfe, 0xfd, 0x09, 0x00, 0x00, 0x00, 0x00 };
// tell the user that we are waiting
Console.WriteLine("Waiting for UDP Connection...");
// Create a new socket to listen from
Socket Skt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Skt.EnableBroadcast = true;
Skt.Bind(new IPEndPoint(IPAddress.Loopback, 27900));
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = new byte[48];
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint senderRemote = (EndPoint)sender;
Skt.ReceiveFrom(receiveBytes, ref senderRemote);
string returnData = Encoding.UTF8.GetString(receiveBytes).Trim();
Console.WriteLine("This is the message you received " + returnData.ToString());
// Sent return data
int sent = Skt.SendTo(ret, senderRemote);
Console.WriteLine("Sent {0} bytes back", sent);
Skt.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
有人请给我一些指点吗?