C# 完整的UDP客戶端程式碼 組播+單播 非同步+同步
阿新 • • 發佈:2019-01-11
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
//接收組播資料
Thread t = new Thread(new ThreadStart(RecvThread));
t.IsBackground = true;
t.Start();
//向組播發送資料
IPEndPoint ipend = new IPEndPoint(IPAddress.Parse("192.168.1.107"), 26215);
UdpClient client = new UdpClient(ipend);
client.EnableBroadcast = false ;
client.JoinMulticastGroup(IPAddress.Parse("239.114.114.106"));
IPEndPoint multicast = new IPEndPoint(IPAddress.Parse("239.114.114.106"), 26214);
byte[] buf = Encoding.Default.GetBytes("<find_server>");
client.Send(buf, buf.Length, multicast);
//非同步接收資料
//client.BeginReceive(new AsyncCallback(ReceiveBack), client);
//設定網路超時時間,一段時間未接收到資料時自動退出
//client.Client.ReceiveTimeout = 150;
//單播接收資料
try
{
while (true)
{
byte[] value = client.Receive(ref ipend);
string msg = Encoding.Default.GetString(value);
Console.WriteLine(msg);
//Console.WriteLine(ipend.Address.ToString());
}
}
catch
{
if(client!=null)
{
client.Close();
client = null;
}
return;
}
}
static void RecvThread()
{
//繫結組播埠
UdpClient client = new UdpClient(26214);
client.EnableBroadcast = false;
client.JoinMulticastGroup(IPAddress.Parse("239.114.114.106"));
IPEndPoint mult = null;
while (true)
{
byte[] buf = client.Receive(ref mult);
string msg = Encoding.Default.GetString(buf);
Console.WriteLine(msg);
//Console.WriteLine(mult.Address.ToString());
}
}
static void ReceiveBack(IAsyncResult state)
{
try
{
UdpClient udpClient = (UdpClient)state.AsyncState;
IPEndPoint endPoint = (IPEndPoint)udpClient.Client.LocalEndPoint;
byte[] receiveBytes = udpClient.EndReceive(state, ref endPoint);
string value = Encoding.Default.GetString(receiveBytes);
Console.WriteLine(value);
//// 在這裡使用非同步委託來處理接收到的陣列,並再次啟動接收
var ar = udpClient.BeginReceive(new AsyncCallback(ReceiveBack), udpClient);
}
catch (Exception e)
{
return;
}
}
}
}