c# - 如何在 C# 中创建 UDP 服务器?

标签 c# udp

<分区>

Possible Duplicate:
C# How to make a simple UDP server

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

最佳答案

这是一个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);
      }
   }
}

关于c# - 如何在 C# 中创建 UDP 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4844581/

相关文章:

c# - 从富文本框中获取选中的文本

c - 为什么这个 uint16_t 变量声明不起作用?

java - 一旦选择器返回,我可以从 channel 读取多少和多长时间?

c - 在c中接收udp文本文件

c# - 返回带有 Ajax 的 PartialView 未在页面上插入

c# - 如何更改 webClient.UploadData() 的时间限制?

c# - 如何将 postsharp 方面应用于网站项目?

c# winform cool colordialog 收藏

java - 当我总共发送 7mb 时,服务器仅收到 16 个 UDP 512 字节数据包

java - 文件 channel 读取/添加错误数据