UDP通讯
Udp通讯:
对于UdpClient类提供了简单的方法用于在组织同步模式下发送和接受无连接的udp数据报。由于Udp是无连接的传输协议。所以不需要在发送和接受数据前建立远程主机连接。但是可以选择两种方法来建立默认的远程主机。
1》使用远程主机名和端口号作为参数创建的UdpClient类的实例。
2》创建UdpClient实例然后调用Connect方法。
话不多说。直接附源码。要是有什么部清除的地方,可以发邮件或者在文章下面问我。我会一一给大家S回答。
发送端:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace DFMT
{
public class Send
{
UdpClient uc = null;
public void SendMsgToIp(string Ip, string msg)
{
uc = new UdpClient(6001);
try
{
//接收者是谁就读取那个端口发送
int port = 9018;
//获得传输的IP地址
IPAddress ip = IPAddress.Parse(Ip);
//将要发送的消息
byte[] bytes = Encoding.UTF8.GetBytes(msg);
//传输的终端IP地址
IPEndPoint sendtoip = new IPEndPoint(ip, port);
//消息传送
uc.Send(bytes, bytes.Length, sendtoip);
//socktSend.SendTo(bytes, sendtoip);
}
catch
{
}
finally
{
uc.Close();
}
}
}
}
接收端:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace DFMT
{
public class Receive
{
public delegate void ReceiveHandler(object sender, Msg message);
public Receive()
{
int port = 9019;
udpclient = new UdpClient(port);
groupIp = new IPEndPoint(IPAddress.Any, port);
}
#region 私有字段
static Thread receiver;
bool done = false;
string message = null;
UdpClient udpclient;
static IPEndPoint groupIp;
#endregion
//声明事件
public event ReceiveHandler ReceiveMessage;
//声明事件引发方法
/// <summary>
/// 事件方法
/// </summary>
public void Start()
{
try
{
//新建一个线程
receiver = new Thread(new ThreadStart(Listen));
//该线程为后台线程
receiver.IsBackground = true;
receiver.Start();
}
catch { }
}
/// <summary>
/// 监听
/// </summary>
private void Listen()
{
try
{
if (!done)
{
//接收数据报文
byte[] bytes = udpclient.Receive(ref groupIp);
message = Encoding.UTF8.GetString(bytes);
Msg msg = new Msg();
msg.Bytes = bytes;
msg.Msge = message;
msg.SourceIP = groupIp.Address.ToString();
if (ReceiveMessage != null)
ReceiveMessage(this, msg);
Start();
}
}
catch { }
}
}
public class Msg : EventArgs
{
private string _msge;
public string Msge
{
get { return _msge; }
set { _msge = value; }
}
private byte[] bytes;
public byte[] Bytes
{
get { return bytes; }
set { bytes = value; }
}
private string sourceIP;
public string SourceIP
{
get { return sourceIP; }
set { sourceIP = value; }
}
}
}