C#UDP(接收和发送源码)源码完整
最近做了一个UDP的服务接收和发送的东西。希望能对初学的朋友一点帮助。
源码如下:
一。逻辑--UdpServer.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Xml.Linq;
using PitchServer.po;
namespace PitchServer.vo
{
class UdpServer
{
#region 构造方法
public UdpServer():this(50000,1024){}
public UdpServer(ushort port):this(port,1024)
{
_Port = port;
}
public UdpServer(ushort port,uint bufferSize)
{
_Port = port;
_bufferSize = bufferSize;
}
#endregion
#region 属性
ushort _Port = 50000;
public ushort Port
{
get { return _Port; }
}
uint _bufferSize = 1024;
public uint BufferSize
{
get{return _bufferSize;}
}
bool m_IsRunning;
public bool IsRunning
{
get{return m_IsRunning;}
}
public static Socket m_UdpServer
{
get;
set;
}
string Ip_Address = "";
#endregion
Thread m_DataReceiveProcThread;
public static List<Client> IpAddress = new List<Client>();
#region 事件定义
public delegate void OnReceivedDataHandler(object sender,DataReceivedEventArgs e);
public event OnReceivedDataHandler OnRecivedData;
public delegate void OnStateChangedHandler(object sender,ServerStateChangeEventArgs e);
public event OnStateChangedHandler OnStateChanged;
#endregion
void DataReceiveProc()
{
while(m_IsRunning)
{
try
{
byte[] data = new byte[BufferSize];
m_UdpServer.Receive(data);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, (int)Port);
EndPoint senderRemote = (EndPoint)ep;
m_UdpServer.ReceiveFrom(data, ref senderRemote);
ep = (IPEndPoint)senderRemote;
Ip_Address=ep.Address.ToString();
bool isexit = false;
for (int i = 0; i < IpAddress.Count; i++)
{
if (Ip_Address == IpAddress[i].IPaddress)
{
isexit = true;
}
}
if (!isexit)
{
Client cl = new Client();
cl.IPaddress = Ip_Address;
cl.Port = ep.Port.ToString();
IpAddress.Add(cl);
}
if(OnRecivedData != null)
OnRecivedData(this, new DataReceivedEventArgs(data, Ip_Address));
System.Threading.Thread.Sleep(100);
}
catch(Exception ex)
{
m_IsRunning = false;
if(OnStateChanged != null)
OnStateChanged(this,new ServerStateChangeEventArgs(false));
throw ex;
}
}
}
public void Stop()
{
if(m_IsRunning)
{
try
{
m_IsRunning = false;
if(OnStateChanged != null)
OnStateChanged(this,new ServerStateChangeEventArgs(m_IsRunning));
m_UdpServer.Shutdown(SocketShutdown.Both);
m_UdpServer.Close();
m_DataReceiveProcThread.Abort();
}
catch(Exception ex)
{
Trace.WriteLine(ex.Message);
}
}
}
public void Start()
{
if(!m_IsRunning)
{
try
{
m_UdpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipep=new IPEndPoint(IPAddress.Any,(int)Port);
m_UdpServer.Bind(ipep);
// m_IsRunning = ThreadPool.QueueUserWorkItem(new WaitCallback(DataReceiveProc));
m_DataReceiveProcThread = new Thread(new ThreadStart(DataReceiveProc));
m_DataReceiveProcThread.Start();
m_IsRunning = true;
if(OnStateChanged != null)
OnStateChanged(this,new ServerStateChangeEventArgs(m_IsRunning));
}
catch(Exception ex)
{
throw ex;
}
}
}
~UdpServer()
{
Stop();
}
}
}
二。前台调用:
开启服务:
UdpServer server = new UdpServer(ushort.Parse(textBox1.Text), 1024);//第一个参数为服务器IP,第二个为规定传输的大小
server.OnRecivedData += new UdpServer.OnReceivedDataHandler(recive);
server.Start();
接收数据的机制:
当客户端发送数据的时候会触发由UdpServer类里的m_DataReceiveProcThread线程接收并触发OnReceivedDataHandler事件,在前台要写这个事件的实现,如下:
private void recive(object sender, EventArgs e)
{
DataReceivedEventArgs DS = (DataReceivedEventArgs)e;
string reciveDate = System.Text.Encoding.UTF8.GetString(DS.Data);//把byte[]转换为 string
}
对指定客户端发送数据:
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(cl.IPaddress), Convert.ToInt32(cl.Port));//cl.IPaddress为客户端IP,cl.Port为客户端的端口
UdpServer.m_UdpServer.Connect(ip);//调用UdpServer的静态SOCKET对象m_UdpServer来连接客户端
UdpServer.m_UdpServer.Send(System.Text.Encoding.UTF8.GetBytes(message));//把要发送的字符串转换为BYTE[]然后发送出去,字符编码要看客户端的解释定义了。