C# UDP 套接字客户端和服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19786668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:53:03  来源:igfitidea点击:

C# UDP Socket client and server

c#socketsudpactivex

提问by Paul

My first question here. I am new to this kind of programming, and i've only programmed .NET web sites and forms.

我的第一个问题在这里。我是这种编程的新手,我只编写过 .NET 网站和表单。

Now, the company I work at, asks me to make an ActiveX component, that listens to UDP messages, and turns them into events.

现在,我工作的公司要求我制作一个 ActiveX 组件,它可以侦听 UDP 消息,并将它们转换为事件。

The UDP msgs are send from Avaya system, so i was told that to test my ActiveX, at first I need to create an app, that only sends UDP (only one button that sends pre-defined UDP string). And then create listener socket, ordinary C# app, that will get those transmitted UDP string from the tests app. Both apps will work on the same machine.

UDP 消息是从 Avaya 系统发送的,所以我被告知要测试我的 ActiveX,首先我需要创建一个仅发送 UDP 的应用程序(只有一个按钮发送预定义的 UDP 字符串)。然后创建侦听器套接字,普通的 C# 应用程序,它将从测试应用程序中获取那些传输的 UDP 字符串。这两个应用程序将在同一台机器上运行。

Later, when i get this working, i need to make the listener an ActiveX component, but first things first.

稍后,当我开始工作时,我需要使侦听器成为 ActiveX 组件,但首先要做的是。

I need to know if there are any good tutorials about this, and any idea on how to start? I am sorry for my ignorance, but i am really new on this and i don't really have any time to learn this since it has to be done in 2 weeks.

我需要知道是否有关于此的任何好的教程,以及有关如何开始的任何想法?我很抱歉我的无知,但我真的很新,我真的没有时间学习这个,因为它必须在 2 周内完成。

Thanks in advance.

提前致谢。

edit: I managed to create 2 simple console applications, and was sending UDP messages between them successfully. The sender will be only for testing, and now I need to re-make my receiver to get the UDP message and 'translate' it to events. And lastly, to make it an ActiveX control...

编辑:我设法创建了 2 个简单的控制台应用程序,并成功地在它们之间发送了 UDP 消息。发送方将仅用于测试,现在我需要重新制作接收方以获取 UDP 消息并将其“翻译”为事件。最后,使它成为一个 ActiveX 控件......

采纳答案by lboshuizen

Simple server and client:

简单的服务器和客户端:

public struct Received
{
    public IPEndPoint Sender;
    public string Message;
}

abstract class UdpBase
{
    protected UdpClient Client;

    protected UdpBase()
    {
        Client = new UdpClient();
    }

    public async Task<Received> Receive()
    {
        var result = await Client.ReceiveAsync();
        return new Received()
        {
            Message = Encoding.ASCII.GetString(result.Buffer, 0, result.Buffer.Length),
            Sender = result.RemoteEndPoint
        };
    }
}

//Server
class UdpListener : UdpBase
{
    private IPEndPoint _listenOn;

    public UdpListener() : this(new IPEndPoint(IPAddress.Any,32123))
    {
    }

    public UdpListener(IPEndPoint endpoint)
    {
        _listenOn = endpoint;
        Client = new UdpClient(_listenOn);
    }

    public void Reply(string message,IPEndPoint endpoint)
    {
        var datagram = Encoding.ASCII.GetBytes(message);
        Client.Send(datagram, datagram.Length,endpoint);
    }

}

//Client
class UdpUser : UdpBase
{
    private UdpUser(){}

    public static UdpUser ConnectTo(string hostname, int port)
    {
        var connection = new UdpUser();
        connection.Client.Connect(hostname, port);
        return connection;
    }

    public void Send(string message)
    {
        var datagram = Encoding.ASCII.GetBytes(message);
        Client.Send(datagram, datagram.Length);
    }

}

class Program 
{
    static void Main(string[] args)
    {
        //create a new server
        var server = new UdpListener();

        //start listening for messages and copy the messages back to the client
        Task.Factory.StartNew(async () => {
            while (true)
            {
                var received = await server.Receive();
                server.Reply("copy " + received.Message, received.Sender);
                if (received.Message == "quit")
                    break;
            }
        });

        //create a new client
        var client = UdpUser.ConnectTo("127.0.0.1", 32123);

        //wait for reply messages from server and send them to console 
        Task.Factory.StartNew(async () => {
            while (true)
            {
                try
                {
                    var received = await client.Receive();
                    Console.WriteLine(received.Message);
                    if (received.Message.Contains("quit"))
                        break;
                }
                catch (Exception ex)
                {
                    Debug.Write(ex);
                }
            }
        });

        //type ahead :-)
        string read;
        do
        {
            read = Console.ReadLine();
            client.Send(read);
        } while (read != "quit");
    }
}

回答by user3520827

Server

服务器

public void serverThread()
{
    UdpClient udpClient = new UdpClient(8080);
    while(true)
    {
        IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
        string returnData = Encoding.ASCII.GetString(receiveBytes);
        lbConnections.Items.Add(RemoteIpEndPoint.Address.ToString() 
                                + ":" +  returnData.ToString());
    }
}

And initialize the thread

并初始化线程

private void Form1_Load(object sender, System.EventArgs e)
{
    Thread thdUDPServer = new Thread(new ThreadStart(serverThread));
    thdUDPServer.Start();
}

Client

客户

private void button1_Click(object sender, System.EventArgs e)
{
    UdpClient udpClient = new UdpClient();
    udpClient.Connect(txtbHost.Text, 8080);
    Byte[] senddata = Encoding.ASCII.GetBytes("Hello World");
    udpClient.Send(senddata, senddata.Length);
}

Insert it to button command.

将其插入按钮命令。

Source: http://technotif.com/creating-simple-udp-server-client-transfer-data-using-c-vb-net/

来源:http: //technotif.com/creating-simple-udp-server-client-transfer-data-using-c-vb-net/

回答by Bachor

Simple server and client:

简单的服务器和客户端:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        // Create UDP client
        int receiverPort = 20000;
        UdpClient receiver = new UdpClient(receiverPort);

        // Display some information
        Console.WriteLine("Starting Upd receiving on port: " + receiverPort);
        Console.WriteLine("Press any key to quit.");
        Console.WriteLine("-------------------------------\n");

        // Start async receiving
        receiver.BeginReceive(DataReceived, receiver);

        // Send some test messages
        using (UdpClient sender1 = new UdpClient(19999))
            sender1.Send(Encoding.ASCII.GetBytes("Hi!"), 3, "localhost", receiverPort);
        using (UdpClient sender2 = new UdpClient(20001))
            sender2.Send(Encoding.ASCII.GetBytes("Hi!"), 3, "localhost", receiverPort);

        // Wait for any key to terminate application
        Console.ReadKey();
    }

    private static void DataReceived(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);

        // Convert data to ASCII and print in console
        string receivedText = ASCIIEncoding.ASCII.GetString(receivedBytes);
        Console.Write(receivedIpEndPoint + ": " + receivedText + Environment.NewLine);

        // Restart listening for udp data packages
        c.BeginReceive(DataReceived, ar.AsyncState);
    }
}