C# UDP Socket client and server

前端 未结 3 1155
忘掉有多难
忘掉有多难 2020-12-04 20:37

My first question here. I am new to this kind of programming, and i\'ve only programmed .NET web sites and forms.

Now, the company I work at, asks me to make an Acti

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 21:03

    Server

    public void serverThread()
    {
        UdpClient udpClient = new UdpClient(8080);
        while(true)
        {
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
            string returnData = Encoding.ASCII.GetString(receiveBytes);
            lbConnections.Items.Add(RemoteIpEndPoint.Address.ToString() 
                                    + ":" +  returnData.ToString());
        }
    }
    

    And initialize the thread

    private void Form1_Load(object sender, System.EventArgs e)
    {
        Thread thdUDPServer = new Thread(new ThreadStart(serverThread));
        thdUDPServer.Start();
    }
    

    Client

    private void button1_Click(object sender, System.EventArgs e)
    {
        UdpClient udpClient = new UdpClient();
        udpClient.Connect(txtbHost.Text, 8080);
        Byte[] senddata = Encoding.ASCII.GetBytes("Hello World");
        udpClient.Send(senddata, senddata.Length);
    }
    

    Insert it to button command.

    Source: http://technotif.com/creating-simple-udp-server-client-transfer-data-using-c-vb-net/

提交回复
热议问题