[英]Receive from UDP Socket and send data back
我正在嘗試編寫一個接受請求的控制台應用程序(大小為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();
}
有人給我一些指示嗎?
以下是我修改過的示例代碼,您可以看到可以從此示例接收和發送。 方法測試作為客戶端,可以是一個不同的過程,現在我已經在不同的線程中進行模擬。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
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;
Thread thr = new Thread(new ThreadStart(Test));
thr.Start();
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();
}
public static void Test()
{
byte[] ret = { 0xfe, 0xfd, 0x09, 0x00, 0x00, 0x00, 0x00 };
Socket Skt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Skt.EnableBroadcast = true;
IPEndPoint test=new IPEndPoint(IPAddress.Loopback, 27900);
int sent = Skt.SendTo(ret, test);
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 ex)
{
}
}
}
}
如果沒有看到您的客戶端代碼,很難確定問題可能在哪里。 我可以使用網絡庫 networkcomms.net為您提供有效的解決方案。 服務器的代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkCommsDotNet;
namespace UPDServer
{
class Program
{
static void Main(string[] args)
{
NetworkComms.AppendGlobalIncomingPacketHandler<string>("Message", (packetHeader, connection, incomingString) =>
{
Console.WriteLine("This is the message you received " + incomingString);
connection.SendObject("Message", incomingString + " relayed by server.");
});
UDPConnection.StartListening(true);
Console.WriteLine("Server ready. Press any key to shutdown server.");
Console.ReadKey(true);
NetworkComms.Shutdown();
}
}
}
對於客戶:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkCommsDotNet;
namespace UDPClient
{
class Program
{
static void Main(string[] args)
{
string messageToSend = "This is a message To Send";
string messageFromServer = UDPConnection.GetConnection(new ConnectionInfo("127.0.0.1", 10000), UDPOptions.None).SendReceiveObject<string>("Message", "Message", 2000, messageToSend);
Console.WriteLine("Server said '{0}'.", messageFromServer);
Console.WriteLine("Press any key to exit.");
Console.ReadKey(true);
NetworkComms.Shutdown();
}
}
}
您顯然需要從網站下載NetworkCommsDotNet DLL,以便您可以在“使用NetworkCommsDotNet”參考中添加它。 另請參閱客戶端示例中的服務器IP地址當前為“127.0.0.1”,如果您在同一台計算機上同時運行服務器和客戶端,這應該可以工作。 有關更多信息,請查看入門或如何創建客戶端服務器應用程序文章。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.