客户端-服务器udp,由于每接到一条消息会开个线程去处理它
话不多说,直接代码
程序代码:
using System;
using System.Text;
using Entity;
namespace NetSocket
{
/// <summary>
/// UDP通讯接收类
/// </summary>
public class UDPReceive
{
/// <summary>
/// 本地端口号
/// </summary>
public int _localPort { get; set; }
/// <summary>
/// 数据报(UDP)对象_接收
/// </summary>
private UdpClient r_client;
/// <summary>
/// 通讯时使用的编码,默认utf8
/// </summary>
private Encoding enCoding = Encoding.UTF8;
/// <summary>
/// 构造函数设置各项默认值
/// </summary>
public UDPReceive()
{
this._localPort = StaticInfo._localPort;
}
/// <summary>
/// 监听本机端口
/// </summary>
public void runReceive()
{
r_client = new UdpClient(this._localPort);
AsyncCallback GetRecvBuffer = new AsyncCallback(ReceiveCallback);
r_client.BeginReceive(GetRecvBuffer, null);
}
/// <summary>
/// 异步执行监听
/// </summary>
/// <param name="ar"></param>
private void ReceiveCallback(IAsyncResult ar)
{
AsyncCallback GetRecvBuffer = new AsyncCallback(ReceiveCallback);
r_client.BeginReceive(GetRecvBuffer, null);
IPEndPoint endpoint = null;
byte[] bytes = r_client.EndReceive(ar, ref endpoint);
string strMsg = enCoding.GetString(bytes);
exeMessage execute = new exeMessage(strMsg);//接到消息然后去别的地方处理的
}
}
}
程序代码:
using System.Text;
using Entity;
namespace NetSocket
{
public class UDPSend
{
/// <summary>
/// 客户端端口号
/// </summary>
private int _clientPort;
/// <summary>
/// 数据报(UDP)对象_发送
/// </summary>
private UdpClient s_client;
/// <summary>
/// 通讯时使用的编码,默认utf8
/// </summary>
private Encoding enCoding = Encoding.UTF8;
public UDPSend()
{
this._clientPort = StaticInfo._clientPort;//设置端口的
}
/// <summary>
/// 向指定地址发送消息
/// </summary>
/// <param name="address">发送地址</param>
/// <param name="bytes">消息字符串</param>
public void sendMessage(string address, string message)
{
if (message == null)
return;
byte[] bytes = enCoding.GetBytes(message);
s_client = new UdpClient();
try
{
s_client.Connect(address, this._clientPort);
s_client.Send(bytes, bytes.Length);
}
catch
{
}
finally
{
s_client.Close();
}
}
/// <summary>
/// 发送消息广播
/// </summary>
/// <param name="message">消息字符串</param>
public void sendBroadcast(string message)
{
//初始化一个Scoket实例,采用UDP传输
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//初始化一个发送广播和指定端口的网络端口实例
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, this._clientPort);
//设置该scoket实例的发送形式
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
byte[] bytes = enCoding.GetBytes(message);
sock.SendTo(bytes, iep);
sock.Close();
}
}
}