最近我开始阅读UDP,我尝试用C#创建自己的应用程序 . 我正在使用Oracle VM ver上的客户端进行测试 . 5.0 . 我为客户端和服务器使用相同的代码(我设置了两个不同的UdpClients用于发送和接收) . The problem 是我在VM上没有收到消息(从我的计算机用Windows 10发送) . 它仅在我从VM向我的系统发送消息时起作用 .
这是代码:
using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
namespace Trevix
{
public partial class Form1 : Form
{
delegate void setText_callback(TextBox txt,string input);
UdpClient client_send,client_receive;
IPEndPoint brodcast_end = new IPEndPoint(IPAddress.Broadcast , 10000);
IPEndPoint listen_end = new IPEndPoint(IPAddress.Any, 0);
Thread listen_thread;
public Form1()
{
InitializeComponent();
//If object initialized with EndPoint or port it will LISTEN(?)
// If I want to send data call CONNECT
client_send = new UdpClient();
client_receive = new UdpClient(10000); //or new UdpClient(listen_end)?
client_send.Connect(brodcast_end);
listen_thread = new Thread(new ThreadStart(listen));
listen_thread.IsBackground = true;
listen_thread.Start();
}
private void button1_Click(object sender, EventArgs e)
{
byte[] buff = Encoding.ASCII.GetBytes(textBox1.Text );
client_send.Send(buff, buff.Length);
}
private void listen()
{
byte[] rec_buff;
IPEndPoint recv_end;
while (true)
{
recv_end = new IPEndPoint(IPAddress.Any, 0);
rec_buff = client_receive.Receive(ref recv_end);
setText(textBox2, recv_end.ToString() +": "+ Encoding.ASCII.GetString(rec_buff)+Environment.NewLine );
}
}
private void setText(TextBox txt, string input)
{
if (txt.InvokeRequired)
{
txt.Invoke(new setText_callback(setText), txt,input);
}
else
{
txt.Text += input;
}
}
}
}
我还有一些其他问题:
1)我也不确定将UdpClient配置为客户端还是服务器 . UdpClient listener=new UdpClient(10000)
和 UdpClient listener=new UdpClient(new IPEndPoint(IPAddress.Any, 0))
之间有什么区别? (我知道'0'作为端口允许类自动分配它) .
2)在这部分代码中
recv_end = new IPEndPoint(IPAddress.Any,0); rec_buff = client_receive.Receive(ref recv_end);
“recv_end”将在运行时被接收器的地址数据(ip和端口)替换 . 但几乎在我在互联网上看到的所有例子中都指出,将终点的ip值设置为Any是至关重要的 . 为什么?