从UDP套接字接收和发送数据回 [英] Receive from UDP Socket and send data back

查看:132
本文介绍了从UDP套接字接收和发送数据回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着写一个控制台应用程序,需要一个请求(大小为18字节),然后送东西(7个字节大小)返回给客户端。我为我的生活似乎无法得到这个工作。我可以接收数据很好,但我送回从未得到的数据到客户端。



下面是我的代码



 静态无效的主要(字符串[]参数)
{
//数据返回
字节[] = RET 0xFE的{,是0xFD,为0x09,0x00时,为0x00,0x00时,0×00};

//告诉我们正在等待
Console.WriteLine(等待UDP连接...)用户;

//创建一个新的socket从
插槽梵文=新的Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp)听;
Skt.EnableBroadcast = TRUE;
Skt.Bind(新IPEndPoint(IPAddress.Loopback,27900));


{
//阻塞,直到一个消息从远程主机此套接字上返回。
字节[] = receiveBytes新的字节[48];
IPEndPoint发件人=新IPEndPoint(IPAddress.Any,0);
端点senderRemote =(端点)发送;

Skt.ReceiveFrom(receiveBytes,楼盘senderRemote);
串returnData = Encoding.UTF8.GetString(receiveBytes).Trim();

Console.WriteLine(这是你收到的消息+ returnData.ToString());

//发送返回数据
INT发送= Skt.SendTo(RET,senderRemote);
Console.WriteLine(已发送{0}字节回,发送);
Skt.Close();
}
赶上(例外五)
{
Console.WriteLine(e.ToString());
}

到Console.ReadLine();
}



任何人给我一些指点吗?


< DIV CLASS =h2_lin>解决方案

没有还看到你的客户端代码,这是很难确定是哪里的问题可能在于。我可以给你使用网络库 networkcomms.net虽然是可行的解决方案。服务器的代码将如下:

 使用系统; 
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
$ B $采用B NetworkCommsDotNet;

命名空间UPDServer
{
类节目
{
静态无效的主要(字串[] args)
{
NetworkComms。 AppendGlobalIncomingPacketHandler<串>(信息,(packetHeader,连接,incomingString)=>
{
Console.WriteLine(这是你收到的消息+ incomingString);
连接。使用SendObject(信息,incomingString +通过服务器中转的。);
});

UDPConnection.StartListening(真);

Console.WriteLine(服务器准备按任意键来关闭服务器。);
Console.ReadKey(真);
NetworkComms.Shutdown();
}
}
}

和客户端:

 使用系统; 
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
$ B $采用B NetworkCommsDotNet;

命名空间UDPClient
{
类节目
{
静态无效的主要(字串[] args)
{
串messageToSend =这是一个消息要发送;
串messageFromServer = UDPConnection.GetConnection(新ConnectionInfo(127.0.0.1,10000),UDPOptions.None).SendReceiveObject<串GT;(信息,消息,2000年,messageToSend);
Console.WriteLine(服务器说:{0}。messageFromServer);

Console.WriteLine(按任意键退出。);
Console.ReadKey(真);
NetworkComms.Shutdown();
}
}
}

您显然需要下载从网站上N​​etworkCommsDotNet DLL,这样就可以在使用NetworkCommsDotNet添加引用它。也看到在客户端的例子服务器的IP地址是目前127.0.0.1,如果你在同一台机器上运行服务器和客户端这应该工作。欲了解更多信息结帐入门或的如何创建一个客户端服务器应用程序的文章。


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.

Here is my code

 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();
    }

Anyone give me some pointers please?

解决方案

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();
        }
    }
}

And for the client:

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();
        }
    }
}

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套接字接收和发送数据回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆