c#udp客户端 - 服务器回显程序

时间:2013-03-30 08:28:34

标签: c# sockets

我刚刚用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

    }

1 个答案:

答案 0 :(得分:3)

我能够通过让客户端直接与服务器对话而不是广播来实现这一点:

var serverAddress = "127.0.0.1"; // Server is on the local machine
IPAddress address = IPAddress.Parse(serverAddress);

...除非我错过了您在原始代码中使用广播的重要原因?