C# UDP server sending and client receiving

UDP Server

private void ServerBroadcastThread()
{
    int GroupPort = 15000;

    UdpClient udp = new UdpClient();
    udp.EnableBroadcast = true;
    IPEndPoint groupEP = new IPEndPoint(IPAddress.Broadcast, GroupPort);

    string str4;
    byte[] sendBytes4;

    while (true)
    {
        str4 = "Is anyone out there?";
        sendBytes4 = Encoding.Default.GetBytes(str4);
        udp.Send(sendBytes4, sendBytes4.Length, groupEP);

        Thread.Sleep(10000);
    }
}

UDP Client

private void ClientBroadcastThread()
{
    UdpClient receivingUdpClient = new UdpClient(15000);
    IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

    string returnData;
    byte[] receiveBytes;

    while (true)
    {
        try
        {
            // Blocks until a message returns on this socket from a remote host.
            receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);

            returnData = Encoding.ASCII.GetString(receiveBytes);

            MessageBox.Show(returnData);
        }
        catch (Exception e)
        {
            //Console.WriteLine(e.ToString());
        }
    }
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料