C# C语言中的UDP客户端#

C# C语言中的UDP客户端#,c#,udp,C#,Udp,我试图用C语言制作一个简单的UDP应用程序,没有什么复杂的东西,连接,发送一些文本,然后接收它!但它一直抛出这个异常 “远程主机已强制关闭现有连接” 守则: byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, So

我试图用C语言制作一个简单的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();

谢谢=)

您是否尝试过检查IP地址是否有效以及端口是否未用于其他用途

窗口:


开始>运行>“
cmd
”>“
ipconfig

尝试关闭防火墙软件。

在调用Receive之前,您应该告诉系统您正在侦听端口9050上的UDP数据包。
添加
server.Bind(ipep)
套接字服务器之后=新套接字(…)

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

这是我对你的代码的建议。可以使用条件使用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();