UDP通讯

上一篇有说到TCP通讯,这篇来谈谈UDP通讯方式

基于Udp协议是无连接模式通讯,占用资源少,响应速度快,延时低。至于可靠性,可通过应用层的控制来满足。(不可靠连接)

(1).建立一个套接字(Socket)

(2).绑定服务器端IP地址及端口号--服务器端

(3).通过SendTo()方法向指定主机发送消息(需提供主机IP地址及端口)

(4).通过ReciveFrom()方法接收指定主机发送的消息(需提供主机IP地址及端口)

UDP通讯方式:建立Socket、绑定IP与端口、发送/接收、结束;

通讯实例

UDP服务器端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading; namespace TcpServerConsoleApp
{
public class UdpServerApp
{
UdpClient _udpc;//UDP客服端
public IPEndPoint _Ipdp; public UdpServerApp()
{
_Ipdp = new IPEndPoint(IPAddress.Parse("192.168.1.142"), );
_udpc = new UdpClient(_Ipdp);
Thread clientThread = new Thread(ReciveFunc);
clientThread.Start(); } private void ReciveFunc()
{
//_Ipdp = new IPEndPoint(IPAddress.Any, 0);
//Console.WriteLine("接入客服端:{0} {1}", _Ipdp.Address.ToString(), _Ipdp.Port.ToString());
while (true)
{
try
{
byte[] buffer = _udpc.Receive(ref _Ipdp); Console.WriteLine("接收信息:{0}", Encoding.Default.GetString(buffer));
}
catch
{ }
}
} public void Sendmsg(string msg)
{
byte[] buf = Encoding.Default.GetBytes(msg);
_udpc.Send(buf, buf.Length, _Ipdp);
} }
}

DUP客服端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading; namespace TcpClientConsolApp
{
public class UdpClientApp
{
UdpClient _udpc;//UDP客服端 public UdpClientApp()
{
_udpc = new UdpClient();
Thread clientThread = new Thread(ReciveFunc);
clientThread.Start(); } private void ReciveFunc()
{
IPEndPoint _Ipdp = new IPEndPoint(IPAddress.Any, );
//Console.WriteLine("接入客服端:{0} {1}", _Ipdp.Address.ToString(), _Ipdp.Port.ToString());
while (true)
{
try
{
byte[] buffer = _udpc.Receive(ref _Ipdp); Console.WriteLine("接收信息:{0}", Encoding.Default.GetString(buffer));
}
catch
{ }
}
} public void Sendmsg(string msg)
{
IPEndPoint servipdt = new IPEndPoint(IPAddress.Parse("192.168.1.142"), );
byte[] buf = Encoding.Default.GetBytes(msg);
_udpc.Send(buf, buf.Length, servipdt);
} }
}

从上面对比可以看出服务端与客服端的代码大致相同。

上一篇:java基础55 UDP通讯协议和TCP通讯协议


下一篇:QUdpSocket-Qt使用Udp通讯实现服务端和客户端