平台:Windows 2003 R2,C#
我有一个应用程序将 UDP 消息发送到自身的其他实例,在同一台计算机和其他计算机上运行。这工作正常。但是,在某些计算机上,侦听器无法听到同一台计算机上的其他线程/进程传输的消息。消息广播ok,网络上的其他机器听到消息,但同一台机器上的监听器听不到消息。
奇怪的是,这发生在我的测试环境中的某些机器上,但不是全部。
编辑:所有失败的机器都安装了 Check Point VPN-1 Securemote 客户端软件。我拿了一台可以工作的机器,安装了 VPN 客户端,现在它不能工作了。请注意,我没有连接到任何 VPN 主机,我只是安装了客户端。
所有机器都有一个网络适配器,子网掩码为 255.255.255.0,IP 地址为 10.3.10.xxx。
这是一个演示问题的测试类。用户键入一些文本,然后将其发送到 10.3.10.255。在某些机器上,ReceiveFrom 返回,而在其他机器上则不返回。我打电话给控制器(“10.3.10.255”,33333)
public class Controller
{
public Controller(IPAddress broadcastAddress, int port)
{
_broadcastAddress = broadcastAddress;
_port = port;
}
public void Start()
{
Socket s = null;
try
{
IPEndPoint _listenEndpoint = new IPEndPoint(IPAddress.Any, _port);
_broadcastEndpoint = new IPEndPoint(_broadcastAddress, _port);
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 10);
s.EnableBroadcast = true;
s.Bind(_listenEndpoint);
SocketState receiveState = new SocketState();
receiveState.s = s;
receiveState.buf = new byte[1024];
EndPoint lep = (EndPoint)_broadcastEndpoint;
s.BeginReceiveFrom(receiveState.buf, 0, receiveState.buf.Length, SocketFlags.None, ref lep, new AsyncCallback(OnReceive), receiveState);
bool done = false;
while (!done)
{
string msg = Console.In.ReadLine();
byte[] msg_bytes = Encoding.ASCII.GetBytes(msg);
if (msg_bytes.Length == 0)
done = true;
else
{
Console.Out.WriteLine("---> {0}", msg);
s.SendTo(msg_bytes, msg_bytes.Length, SocketFlags.None, new IPEndPoint(_broadcastAddress, _port));
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (s != null)
s.Close();
}
}
internal void OnReceive(IAsyncResult ar)
{
SocketState state = ar.AsyncState as SocketState;
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
EndPoint ep = (EndPoint)ipep;
int nRead = state.s.EndReceiveFrom(ar, ref ep);
IPEndPoint myipep = ep as IPEndPoint;
Console.WriteLine("<--- {0} {1}", myipep.Address.ToString(), System.Text.Encoding.ASCII.GetString(state.buf, 0, nRead));
EndPoint lep = (EndPoint)_broadcastEndpoint;
state.s.BeginReceiveFrom(state.buf, 0, state.buf.Length, SocketFlags.None, ref lep, new AsyncCallback(OnReceive), state);
}
IPAddress _broadcastAddress;
int _port = 0;
IPEndPoint _broadcastEndpoint;
}
internal class SocketState
{
internal Socket s;
internal byte[] buf;
}