创建UDP聊天应用程序

时间:2017-01-14 16:32:17

标签: c# sockets udp endpoint

最近我开始阅读有关UDP的内容,并尝试在C#中创建自己的应用程序。我正在使用Oracle VM ver上设置的客户端对其进行测试。 5.0。我为客户端和服务器使用相同的代码(我设置了两个不同的UdpClients用于发送和接收)。 问题是我没有在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是至关重要的。为什么呢?

0 个答案:

没有答案