生活随笔
收集整理的這篇文章主要介紹了
C#实现UDP广播
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
版權聲明:本文為博主原創文章,未經博主允許不得轉載。
向255.255.255.255發送UPD數據包即為UDP廣播,接收端只需綁定UDP廣播的端口號即可得到數據
[csharp] view plaincopy print?
using?System;??using?System.Collections.Generic;??using?System.Linq;??using?System.Text;??using?System.Net;??using?System.Net.Sockets;??using?System.Threading;????namespace?Test??{??????class?Program??????{??????????static?void?Main(string[]?args)??????????{??????????????UdpClient?client?=?new?UdpClient(new?IPEndPoint(IPAddress.Any,?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);??????????????}??????????}??????}??}??
總結
以上是生活随笔為你收集整理的C#实现UDP广播的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。