這裏UDP數據包是我的客戶問題與測試發送與控制檯
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.receive。
-1。您無法連接到可以綁定到的端點。這個概念甚至沒有意義。請不要在這裏發佈純粹的猜測。 – EJP
我沒有連接到我綁定的端點。我告訴他要替換那個代碼... – avi
+1 ..BTW:當前'BeginSendTo'也可以工作,但是我同意'Send'比較好。 –