2009-11-01 62 views
2

我试图发送一个广播,然后让服务器回复成广播:发送答复与插座

public static void SendBroadcast() 
    { 
     byte[] buffer = new byte[1024]; 
     var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
     socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); 

     socket.Connect(new IPEndPoint(IPAddress.Broadcast, 16789)); 
     socket.Send(System.Text.UTF8Encoding.UTF8.GetBytes("Anyone out there?")); 

     var ep = socket.LocalEndPoint; 

     socket.Close(); 

     socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 

     socket.Bind(ep); 
     socket.Receive(buffer); 
     var data = UTF8Encoding.UTF8.GetString(buffer); 
     Console.WriteLine("Got reply: " + data); 

     socket.Close(); 
    } 

    public static void ReceiveBroadcast() 
    { 
     byte[] buffer = new byte[1024]; 

     var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
     var iep = new IPEndPoint(IPAddress.Any, 16789); 
     socket.Bind(iep); 

     var ep = iep as EndPoint; 
     socket.ReceiveFrom(buffer, ref ep); 
     var data = Encoding.UTF8.GetString(buffer); 

     Console.WriteLine("Received broadcast: " + data + " from: " + ep.ToString()); 

     buffer = UTF8Encoding.UTF8.GetBytes("Yeah me!"); 
     socket.SendTo(buffer, ep); 

     socket.Close(); 
    } 

广播到达罚款,但答复没有。没有例外被抛出。谁能帮我?我是否必须为回复或其他内容打开新的连接?

编辑:改变了我的代码了一下,现在它的工作!感谢您的回复!

回答

4

它看起来不像你的SendBroadcast()套接字绑定到一个端口,所以他不会收到任何东西。事实上,你的ReceiveBroadcast()套接字将回复发送回他自己的端口,所以他将收到他自己的回复。

ReceiveBroadcast: binds to port 16789 
SendBroadcast: sends to port 16789 
ReceiveBroadcast: receives datagram on port 16789 
ReceiveBroadcast: sends reply to 16789 
ReceiveBroadcast: **would receive own datagram if SendTo follwed by Receive** 

你需要(一)有SendBroadcast()绑定到不同端口和改变ReceiveBroadcast()发送到端口(而不是他自己的端点ep),或(b)有两个功能使用相同的Socket对象所以他们可以接收数据包在端口16789.

+0

你说得对,谢谢! – eWolf 2009-11-01 19:04:14