这是我的客户代码
class Program
{
static void Main(string[] args)
{
string msg;
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 999);
sck.Bind(ep);
byte[] msgbytes;
while (true)
{
msg = Console.ReadLine();
msgbytes = ASCIIEncoding.ASCII.GetBytes(msg);
sck.BeginSendTo(msgbytes, 0, msgbytes.Length, SocketFlags.None, ep, null, sck);
Console.WriteLine("sent");
}
}
void callBack(IAsyncResult result)
{
((Socket)result.AsyncState).EndSendTo(result);
}
}
}
这是服务器代码
class Program
{
static void Main(string[] args)
{
string msg;
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 999);
sck.Bind(ep);
byte[] msgbytes = new byte[100];
EndPoint client = (EndPoint)ep;
int bytesrec;
while (true)
{
bytesrec = sck.ReceiveFrom(msgbytes, 0, msgbytes.Length, SocketFlags.None, ref client);
msg = ASCIIEncoding.ASCII.GetString(msgbytes);
Console.WriteLine("4");
}
}
}
}
问题是当我尝试与客户端发送时,服务器没有收到任何数据包。“4”从未被写入,这确认 sck.receivefrom 已执行。