【问题标题】:How do I make a UDP Server in C#? [duplicate]如何在 C# 中创建 UDP 服务器? [复制]
【发布时间】:2011-01-30 18:13:17
【问题描述】:

可能重复:
C# How to make a simple UDP server

我想用 C# 制作一个 UDP 服务器。我怎么做?如何自定义监听哪个端口(即 1212)?

【问题讨论】:

标签: c# udp


【解决方案1】:

这是sample in C#

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class UdpSrvrSample
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
      UdpClient newsock = new UdpClient(ipep);

      Console.WriteLine("Waiting for a client...");

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

      data = newsock.Receive(ref sender);

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

      string welcome = "Welcome to my test server";
      data = Encoding.ASCII.GetBytes(welcome);
      newsock.Send(data, data.Length, sender);

      while(true)
      {
         data = newsock.Receive(ref sender);

         Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));
         newsock.Send(data, data.Length, sender);
      }
   }
}

【讨论】:

  • 如果你不想冻结你的winform ui,你可以使用线程类。线程th = 新线程th = 新线程(() => { UDPServerInitAndListen(); }); th.IsBackground = true; th.Start();
猜你喜欢
  • 2012-06-01
  • 2014-05-18
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
  • 2016-02-26
  • 2011-05-05
  • 2019-09-08
  • 2012-11-28
相关资源
最近更新 更多