對於套接字和C#一般來說我是新來的,並且在實現一個簡單的upd監聽器函數時遇到困難。我花了很多時間在網上搜索,結果沒有成功地在網上插入任何數字例子。所以,任何建議,鏈接,例子將不勝感激!使用套接字的UDP監聽器生成類型錯誤
此時,我有第三方應用程序通過端口6600廣播一個包含有關應用程序服務器位置信息(服務器名稱,IP地址等)的常規UPD消息。我想設計我的偵聽客戶端應用程序來捕獲UPD廣播並生成可用於未來處理的可用服務器的集合。
我遇到的問題是,當我嘗試使用listener.Listen(0)創建偵聽器時,如果失敗並生成一般類型錯誤。如果我嘗試使用UdpClient類,我的應用程序將掛起並且不會返回任何數據。守則兩個例子如下表所示:
namespace UDPListener
{
class Program
{
static void Main(string[] args)
{
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
listener.Bind(new IPEndPoint(IPAddress.Any, 6600));
listener.Listen(6);
Socket socket = listener.Accept();
Stream netStream = new NetworkStream(socket);
StreamReader reader = new StreamReader(netStream);
string result = reader.ReadToEnd();
Console.WriteLine(result);
socket.Close();
listener.Close();
}
}
}
而且UdpClient:
private void IdentifyServer()
{
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient(6600);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Output.Text = ("This is the message you received " +
returnData.ToString());
Output.Text = ("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
你混淆UDP和TCP。簡而言之,UDP基於Bind,ReceiveFrom和SendTo,而TCP使用綁定,監聽,接受,連接,發送和接收以及流等。查看MSDN以及那裏的示例,以瞭解UDP的工作原理。 – dtb
你有使用UDP協議與TCP協議的具體原因嗎? – Dan
謝謝,對於這篇文章!我想我可能實現了UPD錯誤,但是msdn上的例子並沒有太多幫助...... UdpClient例子與msdn網站上的例子幾乎完全相同。它的問題是它停止並掛起,從不捕獲任何數據。 – Simpleton