C#中的UDP客户端

时间:2010-11-17 16:39:05

标签: c# udp

我试图使用C sharp创建一个简单的UDP应用程序,没有复杂,连接,发送一些文本,并接收它!但它一直在抛出这个例外!

“远程主机强行关闭现有连接”!

代码:

     byte[] data = new byte[1024];
    IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);

    Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

    string welcome = "Hello, are you there?";
    data = Encoding.ASCII.GetBytes(welcome);
    server.SendTo(data, data.Length, SocketFlags.None, ipep);

    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint tmpRemote = (EndPoint)sender;

   data = new byte[1024];
    int recv = server.ReceiveFrom(data, ref tmpRemote);

    Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
    Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));



    Console.WriteLine("Stopping client");
    server.Close();

thanks =)

4 个答案:

答案 0 :(得分:2)

在调用Receive之前,您应该告诉系统您正在侦听端口9050上的UDP数据包。 在server.Bind(ipep);

之后添加Socket server = new Socket(...);

答案 1 :(得分:0)

您是否尝试检查IP地址是否有效且该端口未用于其他内容?

<强>窗:

开始&gt;运行&gt; “cmd”&gt; “ipconfig”。

答案 2 :(得分:0)

尝试关闭防火墙软件。

答案 3 :(得分:0)

如果您不知道应答服务器的IP,最好: recv = server.Receive(data);

以下是我对您的代码的建议。你可以使用一个使用条件的do-while循环(在我的例子中它是一个无限循环):

        byte[] data = new byte[1024];
        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);

        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        string welcome = "Hello, are you there?";
        data = Encoding.ASCII.GetBytes(welcome);
        server.ReceiveTimeout = 10000; //1second timeout
        int rslt =  server.SendTo(data, data.Length, SocketFlags.None, ipep);

        data = new byte[1024];
        int recv = 0;
        do
        {
            try
            {
                Console.WriteLine("Start time: " + DateTime.Now.ToString());
                recv = server.Receive(data); //the code will be stoped hier untill the time out is passed
            }
            catch {  }
        } while (true); //carefoul! infinite loop!

        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
        Console.WriteLine("Stopping client");
        server.Close();