UDP(User Datagram Protocol,用户数据报协议)是在互联网中常用的传输层协议,该协议提供了向另一用户程序发送的消息的最简便的协议机制。与TCP一样,其默认的下层协议是IP.UDP是面向操作的,不提供提交和复制保护,因此不能保证数据的可靠性传输。UDP一般用在可靠性较高的局域网中。
.NET 下可使用Socket 类编写基于UDP的网络程序,只要在创建Socket时将构造函数函数的第三个参数选为枚举值ProtocolType.Udp即可.此外,.NET的System.Net.Sockets命名空间下还有一个UdpClient类,可专门用于UDP的网络编程。-----摘自< C#.NET 框架高级编程技术案例教程 郭文夷等 P163>
第一种,使用Socket类
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text));
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
serverSocket.Bind(ip);
第二种,使用UdpClient类
IPAddress address = IPAddress.Parse(txtLocalIp.Text);
int port = Int32.Parse(txtLocalPort.Text);
IPEndPoint endPoint = new IPEndPoint(address, port);
UdpClient udpClient = new UdpClient(endPoint);
-------------------------------------------------------------------这里是分割线-----------------------------------------------
本文主要采用第一种,基于Socket编写一个Udp发包程序。服务器端不断发包,客户端根据接收到的点数据在窗体上绘制点,效果如下所示:
一.服务器端
1.创建一个Socket对象,绑定服务器端Ip和端口号。
2.创建一个线程用户获取客户机的Ip和端口号。大致是这样的,客户机连接到服务器,同时发送一个"你好"的消息,服务器端这样就可以获取到客户机的Ip和端口。
private void btnStart_Click(object sender, EventArgs e)
{
if (serverSocket != null)
{
return;
}
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text));
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
serverSocket.Bind(ip); AppendTextToTxtLog(string.Format("服务器端是{0},正在等待客户端的连接",ip.ToString()));
Thread thread = new Thread(ReceiveData);
thread.IsBackground = true;
thread.Start(); }
3.发送数据
private void SendData()
{
byte[] data = new byte[ * ];
int j = ;
Random r = new Random();
while (j >)
{
j--;
int x = r.Next();
int y = r.Next();
string msg = x.ToString() +","+ y.ToString();
data = Encoding.Default.GetBytes(msg);
for (int k = ; k < RemoteList.Count; k++)
{
int i = serverSocket.SendTo(data, data.Length, SocketFlags.None,RemoteList[k]);
AppendTextToTxtLog(string.Format("发送给客户端{0}的消息是{1}", RemoteList[k].ToString(), msg));
}
}
}
客户端
1.连接到服务器端
private void btnConnected_Click(object sender, EventArgs e)
{
byte[] data = new byte[]; IPEndPoint ip = new IPEndPoint(IPAddress.Parse("192.168.10.179"), );
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "你好!";
data = Encoding.Default.GetBytes(welcome);
ServerSocket.SendTo(data, data.Length, SocketFlags.None, ip);
Thread thread = new Thread(ReceiveData);
thread.IsBackground = true;
thread.Start();
}
2.接受数据
/// <summary>
/// 接受消息
/// </summary>
private void ReceiveData()
{
byte[] data = new byte[];
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, );
EndPoint remote = (EndPoint)endPoint;
while (true)
{
int len = ;
try
{
len = ServerSocket.ReceiveFrom(data, ref remote);
string str = Encoding.Default.GetString(data, , len);
string[] points = str.Split(',');
int x = int.Parse(points[]);
int y = int.Parse(points[]);
Point p = new Point(x, y);
Thread thread = new Thread(new ParameterizedThreadStart(drawPoint));
thread.IsBackground = true;
thread.Start(p);
}
catch (Exception ex)
{ }
} }
3.绘制
/// <summary>
/// 绘制
/// </summary>
/// <param name="p"></param>
public void drawPoint(object p)
{ Point point = (Point)p;
Graphics g = this.panel1.CreateGraphics();
Pen pen = new Pen(Color.Black);
g.DrawEllipse(pen, point.X, point.Y, , );
}
源码下载: http://download.csdn.net/detail/gongchao1212/9591239