在工作中,我必须路由一些使用UDP进入的数据。我已经学习了一些教程,如this blog或this tutorial,并制作了两个控制台应用程序,一个发送UDP消息(客户端),另一个读取它们(监听器)。 当我输入IP地址127.0.0.1(本地主机)一切顺利,但没有其他地址的作品。如果我使用我真正的本地IP地址,我没有运气。由于我本地没有静态IP,我也尝试在有静态IP的服务器上安装侦听器。为此,我已经确保将规则添加到Windows防火墙入站规则集。仍然没有运气。有任何想法吗?这里是我的代码:UDP到服务器不起作用
/西蒙/
客户
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时不显示呢?基于这个新的信息,建议为什么听众没有收到任何数据?
/simon/
您的疑难解答数据包捕获是什么样的? – admdrew
您的错误报告只包含“不起作用”或“没有运气”等短语。怎么了?你有错误吗?套接字是否被创建? –