C# UDP 客户端-服务器回声程序

4
我刚开始学习C#中的套接字编程。我想开发一个简单的客户端-服务器回声应用程序。我遇到的问题是当我尝试将消息回送给客户端时,它无法接收到。我花费了很多时间在各种论坛上搜索解决方案,但都找不到能帮助我解决问题的答案。
提前感谢。 安德鲁
以下是代码:
服务器:
    static void Main(string[] args)
    {

        string data = "";

        UdpClient server = new UdpClient(8008);


        IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);


        Console.WriteLine(" S E R V E R   IS   S T A R T E D ");
        Console.WriteLine("* Waiting for Client...");
        while (data != "q")
        {
            byte[] receivedBytes = server.Receive(ref remoteIPEndPoint);
            data = Encoding.ASCII.GetString(receivedBytes);
            Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");
            Console.WriteLine("Message Received " + data.TrimEnd());

            server.Send(receivedBytes, receivedBytes.Length,remoteIPEndPoint);
            Console.WriteLine("Message Echoed to" + remoteIPEndPoint + data);
        }

        Console.WriteLine("Press Enter Program Finished");
        Console.ReadLine(); //delay end of program
        server.Close();  //close the connection
    }
}

客户端:

    static void Main(string[] args)
    {


        string data = "";
        byte[] sendBytes = new Byte[1024];
        byte[] rcvPacket = new Byte[1024];
        UdpClient client = new UdpClient();
        IPAddress address = IPAddress.Parse(IPAddress.Broadcast.ToString());
        client.Connect(address, 8008);
        IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);

        Console.WriteLine("Client is Started");
        Console.WriteLine("Type your message");

        while (data != "q")
        {
            data = Console.ReadLine();
            sendBytes = Encoding.ASCII.GetBytes(DateTime.Now.ToString() + " " + data);
            client.Send(sendBytes, sendBytes.GetLength(0)); 
            rcvPacket = client.Receive(ref remoteIPEndPoint);

            string rcvData = Encoding.ASCII.GetString(rcvPacket);
            Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");

            Console.WriteLine("Message Received: " + rcvPacket.ToString());
        }
        Console.WriteLine("Close Port Command Sent");  //user feedback
        Console.ReadLine();
        client.Close();  //close connection

    }

你尝试过用两台电脑吗? - Guy P
很遗憾,我只有一台电脑。 - user2226679
所以我认为你做不到, 请在两台不同的电脑上尝试运行你的程序。 - Guy P
4
当然,他可以在一台电脑上完成这件事! - Axarydax
那正是我所想的。 - user2226679
客户端部分的字节数组声明有点误导,因为它们的初始实例化没有被引用。像 byte[] sendBytes = null, rcvPacket = null; 这样的写法会更简单明了。 - maxp
1个回答

4
我通过让客户端直接与服务器通信而不是广播,成功地使其工作:
var serverAddress = "127.0.0.1"; // Server is on the local machine
IPAddress address = IPAddress.Parse(serverAddress);

除非我错过了您在原始代码中使用广播的重要原因,否则建议不要使用广播。

非常感谢你,Oli,你的解决方案很有效 :) 我早该意识到这个问题了,我真是太菜了 :P.. - user2226679

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接