0%

UDP

前面啥也没有

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
static void Main(string[] args)  
{
UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 0));//不指定网卡、端口发送
client = new UdpClient(new IPEndPoint(IPAddress.Parse("1.1.1.1"), 0));//设置网卡发送
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 7788);
byte[] buf = Encoding.Default.GetBytes("Hello from UDP broadcast");
Thread t = new Thread(new ThreadStart(RecvThread));
t.IsBackground = true;
t.Start();
while (true)
{
client.Send(buf, buf.Length, endpoint);
Thread.Sleep(1000);
}
}

static void RecvThread()
{
UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 7788));
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
byte[] buf = client.Receive(ref endpoint);
string msg = Encoding.Default.GetString(buf);
Console.WriteLine(msg);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/// <summary>
/// 发送UDP消息
/// </summary>
/// <param name="msg">消息内容</param>
void Send(string msg)
{
UdpClient udpClient = new UdpClient();
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Broadcast, 10249);
// IPAddress.Broadcast 就是 255.255.255.255
byte[] buffer = Encoding.UTF8.GetBytes(msg);
udpClient.Send(buffer, buffer.Length, ipEndPoint);
}

static void Main()
{
UdpClient udpServer = new UdpClient(10249);
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 10249);

udpServer.BeginReceive(Received, udpServer);
}

/// <summary>
/// 异步接收UDP数据
/// </summary>
/// <param name="iar"></param>
void Received(IAsyncResult iar)
{
  udpServer = iar.AsyncState as UdpClient;
  byte[] buffer = udpServer.EndReceive(iar, ref ipEndPoint);

  //将获取的byte[]数据转换成字符串
  string m = Encoding.UTF8.GetString(buffer).Trim();

  Console.WriteLine("Receive:{0}",m);

  //继续异步接收数据
  udpServer.BeginReceive(Received, udpServer);
}