UDP通讯
服务端
Code
public class Udpserver
{
public UdpClient udpClient;
public Thread UdpThread;
public Udpserver()
{
if (udpClient != null)
{
UdpThread.Abort();
udpClient.Close();
}
//服务端监听接受数据
try
{
udpClient = new UdpClient(8042);
UdpThread = new Thread(new ThreadStart(UdpReciveThread));
UdpThread.Start();
}
catch (Exception y)
{
udpClient.Close();
UdpThread.Abort();
}
}
#region 处理事件
public void UdpReciveThread()
{
IPEndPoint poin = new IPEndPoint(IPAddress.Any, 8042);
while (udpClient != null && Thread.CurrentThread.ThreadState.Equals(ThreadState.Running))
{
try
{
byte[] buf = udpClient.Receive(ref poin);
string bufs = Encoding.UTF8.GetString(buf);
string order = bufs.Split('|')[0].ToString();
string sernews = bufs.Split('|')[1].ToString();
switch(order)
{
case "UserLogin"://登陆
break;
case "UserMove"://移动
break;
case "UserExit"://退出
break;
default:
break;
}
}
catch {
}
}
}
#endregion
}
public class Udpserver
{
public UdpClient udpClient;
public Thread UdpThread;
public Udpserver()
{
if (udpClient != null)
{
UdpThread.Abort();
udpClient.Close();
}
//服务端监听接受数据
try
{
udpClient = new UdpClient(8042);
UdpThread = new Thread(new ThreadStart(UdpReciveThread));
UdpThread.Start();
}
catch (Exception y)
{
udpClient.Close();
UdpThread.Abort();
}
}
#region 处理事件
public void UdpReciveThread()
{
IPEndPoint poin = new IPEndPoint(IPAddress.Any, 8042);
while (udpClient != null && Thread.CurrentThread.ThreadState.Equals(ThreadState.Running))
{
try
{
byte[] buf = udpClient.Receive(ref poin);
string bufs = Encoding.UTF8.GetString(buf);
string order = bufs.Split('|')[0].ToString();
string sernews = bufs.Split('|')[1].ToString();
switch(order)
{
case "UserLogin"://登陆
break;
case "UserMove"://移动
break;
case "UserExit"://退出
break;
default:
break;
}
}
catch {
}
}
}
#endregion
}
客户端发送:
Code
UdpClient uc = new UdpClient("127.0.0.1",8042);
byte[] sendbuf = Encoding.UTF8.GetBytes("abcd11111");
uc.Send(sendbuf, sendbuf.Length);
UdpClient uc = new UdpClient("127.0.0.1",8042);
byte[] sendbuf = Encoding.UTF8.GetBytes("abcd11111");
uc.Send(sendbuf, sendbuf.Length);