c#client-server使用UDP连接

时间:2015-09-06 20:38:32

标签: c#

我正在尝试在c#中进行客户端服务器应用。在客户端,我向服务器和服务器写入hello消息接收消息。 一旦服务器收到消息,它应该向客户端发送一个指示已收到消息的消息。基本上是一种承认。 我的问题是客户端没有从服务器接收消息。 On down是我的客户端和服务器代码。

客户端部分:

string x = "192.168.1.4";
IPAddress add = IPAddress.Parse(x);
IPEndPoint point = new IPEndPoint(add, 2789);

using (UdpClient client = new UdpClient())
{
    byte[] data = Encoding.UTF8.GetBytes("Hello from client");
    client.Send(data, data.Length, point); 

    string serverResponse = Encoding.UTF8.GetString(client.Receive(ref point));

    Console.WriteLine("Messahe received from server:"+ serverResponse);
}

服务器部分:

try
{
    while (true)
    {
        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 2789);
        Console.WriteLine("Client address is:" + groupEP.Address.ToString());
        Console.WriteLine("Client port is:" + groupEP.Port.ToString()); 

        byte[]data = new byte[1024];
        UdpClient listener = new UdpClient(2789);

        Console.WriteLine("Waiting for client");
        byte[] bytes = listener.Receive(ref groupEP);
        Console.WriteLine("Received Data:"+ Encoding.ASCII.GetString(bytes, 0, bytes.Length));

        //sending acknoledgment
        string welcome = "Hello how are you from server?";
        byte[]d1 = Encoding.ASCII.GetBytes(welcome);
        listener.Send(d1, d1.Length, groupEP);
        Console.WriteLine("Message sent to client back as acknowledgment");
    }
}

1 个答案:

答案 0 :(得分:0)

我编译了你的代码并且它有效,所以你的问题是"外部"问题如:

  • 防火墙阻止了某些事情(连接或服务器绑定)。

  • 您在与服务器不同的计算机上测试客户端并使用错误的IP 如果您在同一台计算机上进行测试,则可以使用特殊的ip 127.0.0.1(也称为DNS localhost)。 127.0.0.1始终引用运行代码的计算机。如果您的本地IP确实发生了变化,使用这个特殊的IP可以避免将来出现问题。

顺便说一句,在您的服务器代码中,您应该重用" listener" while()的每个交互的字段,例如

        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 2789);
        Console.WriteLine("Client address is:" + groupEP.Address.ToString());
        Console.WriteLine("Client port is:" + groupEP.Port.ToString());

        byte[] data = new byte[1024];
        UdpClient listener = new UdpClient(2789);

        while (true)
        {
            Console.WriteLine("Waiting for client");
            byte[] bytes = listener.Receive(ref groupEP);
            Console.WriteLine("Received Data:" + Encoding.ASCII.GetString(bytes, 0, bytes.Length));

            //sending acknoledgment
            string welcome = "Hello how are you from server?";
            byte[] d1 = Encoding.ASCII.GetBytes(welcome);
            listener.Send(d1, d1.Length, groupEP);
            Console.WriteLine("Message sent to client back as acknowledgment");

        }