开发者

How do I make a UDP Server in C#? [duplicate]

开发者 https://www.devze.com 2023-02-07 07:35 出处:网络
This question already has answers here: Closed 10 years ago. 开发者_如何学PythonPossible Duplicate:
This question already has answers here: Closed 10 years ago.
开发者_如何学Python

Possible Duplicate:

C# How to make a simple UDP server

I want to make a UDP server in C#. How do I do that? How can I customize which port it listens on (namely 1212)?


Here is a 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);
      }
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消