在工作中,我必须路由一些使用UDP进入的数据。我已经遵循了一些教程,例如this blog或this tutorial,并编写了两个控制台应用程序,一个用于发送UDP消息(客户端),另一个用于读取它们(侦听器)。 当我输入IP地址127.0.0.1(localhost)时一切顺利,但没有其他地址有效。如果我使用我真正的本地IP地址,我没有运气。由于我本地没有静态IP,我也尝试在具有静态IP的服务器上安装监听器。在这样做的过程中,我确保将规则添加到Windows防火墙入站规则集中。仍然没有运气。有任何想法吗?这是我的代码:
/西蒙/
客户端
class Client
{
private readonly Socket _sendingSocket;
private readonly IPEndPoint _receiverEndpoint;
private static int outboundPortNumber = int.Parse(ConfigurationManager.AppSettings["OutgoingPortNumber"]);
public Client()
{
var receiverAddress = IPAddress.Parse(ConfigurationManager.AppSettings["IpOfReceiver"]);
_receiverEndpoint = new IPEndPoint(receiverAddress, outboundPortNumber);
_sendingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_sendingSocket.EnableBroadcast = true;
}
public void Transmit()
{
bool done = false;
while (!done)
{
Console.WriteLine("Hit q to quit");
var keypress = Console.ReadKey();
if (keypress.KeyChar.ToString().ToLower() == "q")
done = true;
else
SendTextToServer();
}
}
private void SendTextToServer()
{
Console.WriteLine("Enter text to send");
var textToSend = Console.ReadLine();
byte[] send_buffer = Encoding.ASCII.GetBytes(textToSend);
try
{
_sendingSocket.SendTo(send_buffer, _receiverEndpoint);
}
catch (Exception send_exception)
{
Console.WriteLine(" Exception {0}", send_exception.Message);
}
}
}
监听
class Listener
{
private bool _started;
private ManualResetEvent _stop;
private UdpClient _client;
private IPEndPoint _endPoint;
private Thread _workingThread;
private static int inboundPortNumber = int.Parse(ConfigurationManager.AppSettings["IncomingPortNumber"]);
public void Start()
{
_started = true;
_stop = new ManualResetEvent(false);
InitializeUdpClient();
InitializeWorkingThread();
}
private void InitializeUdpClient()
{
_endPoint = new IPEndPoint(IPAddress.Any, inboundPortNumber);
_client = new UdpClient(_endPoint);
}
private void InitializeWorkingThread()
{
_workingThread = new Thread(WorkerFunction);
_workingThread.Name = "WorkingThread";
_workingThread.Start();
}
private void WorkerFunction()
{
while (_started)
{
var res = _client.BeginReceive(iar =>
{
if (iar.IsCompleted)
{
byte[] receivedBytes = _client.EndReceive(iar, ref _endPoint);
OutputToConsole(receivedBytes);
}
}, null);
if (WaitHandle.WaitAny(new[] { _stop, res.AsyncWaitHandle }) == 0)
{
break;
}
}
}
private void OutputToConsole(byte[] receivedBytes)
{
string receivedPacket = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine("{0} received at {1}", receivedPacket, DateTime.Now.ToString("hhMMss.ffff"));
}
}
- 编辑 -
其中一条评论建议我应该查看一些日志记录。使用Microsoft网络监视器捕获我的数据流量,我尝试了以下内容: (1)在开发机器上:从我的开发机器发送到127.0.0.1(因此从localhost到localhost)时,不会记录任何数据。我觉得这很奇怪,因为这是接收消息并很好地打印到控制台的唯一场景。 (2)当我从我的开发机器发送到服务器时,在我的开发机器上捕获了一些出站数据,在服务器上也有传入数据。我在服务器上运行了netstat -b,它根本没有显示任何UDP协议。因为在方法InitializeUdpClient()中,UdpClient具有IPEndpoint所以我应该绑定到端口。为什么我运行netstat时不显示?根据这个新信息,有一个建议,为什么听众没有收到任何数据?
/西蒙/
答案 0 :(得分:0)
西蒙