从 UDP Socket 接收并发送回数据

Receive from UDP Socket and send data back(从 UDP Socket 接收并发送回数据)
本文介绍了从 UDP Socket 接收并发送回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个控制台应用程序,它接受一个请求(大小为 18 字节),然后将某些内容(大小为 7 字节)发送回客户端.我这辈子似乎无法让它发挥作用.我可以很好地接收数据,但我发回的数据永远不会到达客户端.

I'm trying to write a console application that takes a request (size is to be 18 bytes), and then send something (size of 7 bytes) back to the client. I for the life of me can't seem to get this to work. I can receive the data fine, but the data I send back never gets to the client.

这是我的代码

 static void Main(string[] args)
 {
        // Data to return
        byte[] ret = { 0xfe, 0xfd, 0x09, 0x00, 0x00, 0x00, 0x00 };

        // tell the user that we are waiting
        Console.WriteLine("Waiting for UDP Connection...");

        // Create a new socket to listen from
        Socket Skt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        Skt.EnableBroadcast = true;
        Skt.Bind(new IPEndPoint(IPAddress.Loopback, 27900));

        try
        {
            // Blocks until a message returns on this socket from a remote host.
            Byte[] receiveBytes = new byte[48];
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint senderRemote = (EndPoint)sender;

            Skt.ReceiveFrom(receiveBytes, ref senderRemote);
            string returnData = Encoding.UTF8.GetString(receiveBytes).Trim();

            Console.WriteLine("This is the message you received " + returnData.ToString());

            // Sent return data
            int sent = Skt.SendTo(ret, senderRemote);
            Console.WriteLine("Sent {0} bytes back", sent);
            Skt.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.ReadLine();
    }

有大神指点一下吗?

推荐答案

如果不查看您的客户端代码,就很难确定问题可能出在哪里.不过,我可以使用 网络库 networkcomms.net 为您提供一个可行的解决方案.服务器的代码如下:

Without also seeing your client code it's difficult to be sure where the problem might lie. I can give you a working solution using the network library networkcomms.net though. The code for the server would be as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NetworkCommsDotNet;

namespace UPDServer
{
    class Program
    {
        static void Main(string[] args)
        {
            NetworkComms.AppendGlobalIncomingPacketHandler<string>("Message", (packetHeader, connection, incomingString) => 
            {
                Console.WriteLine("This is the message you received " + incomingString);
                connection.SendObject("Message", incomingString + " relayed by server.");
            });

            UDPConnection.StartListening(true);

            Console.WriteLine("Server ready. Press any key to shutdown server.");
            Console.ReadKey(true);
            NetworkComms.Shutdown();
        }
    }
}

对于客户来说:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NetworkCommsDotNet;

namespace UDPClient
{
    class Program
    {
        static void Main(string[] args)
        {
            string messageToSend = "This is a message To Send";
            string messageFromServer = UDPConnection.GetConnection(new ConnectionInfo("127.0.0.1", 10000), UDPOptions.None).SendReceiveObject<string>("Message", "Message", 2000, messageToSend);
            Console.WriteLine("Server said '{0}'.", messageFromServer);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey(true);
            NetworkComms.Shutdown();
        }
    }
}

您显然需要从网站下载 NetworkCommsDotNet DLL,以便将其添加到使用 NetworkCommsDotNet"参考中.另请参阅客户端示例中的服务器 IP 地址当前为127.0.0.1",如果您在同一台机器上同时运行服务器和客户端,这应该可以工作.有关更多信息,请查看 入门 或 如何创建客户端服务器应用程序 文章.

You will obviously need to download the NetworkCommsDotNet DLL from the website so that you can add it in the 'using NetworkCommsDotNet' reference. Also see the server IP address in the client example is currently "127.0.0.1", this should work if you run both the server and client on the same machine. For more information checkout the getting started or how to create a client server application articles.

这篇关于从 UDP Socket 接收并发送回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)