因为TCP的异步操作已经做好了,现在再加个UDP协议的异步通信系统;因为UDP不用连接的所以比较方便;我看到有些例子不是很懂,接收数据是用serverSocket.BeginReceiveFrom还是serverSocket.BeginReceive;二个东东有啥区别,还有UDP异步发送的时候 用什么函数;最好有比较简单的例子 谢谢
UDP服务器:
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleUdpServer
{
class Program
{
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
EndPoint localEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8002);
socket.Bind(localEP);
//启动异步接收
State state = new State(socket);
socket.BeginReceiveFrom(
state.Buffer, 0, state.Buffer.Length,
SocketFlags.None,
ref state.RemoteEP,
EndReceiveFromCallback,
state);
Console.ReadLine();
socket.Close();
}
//异步接收回调函数
static void EndReceiveFromCallback(IAsyncResult iar)
{
State state = iar.AsyncState as State;
Socket socket = state.Socket;
try
{
//完成接收
int byteRead = socket.EndReceiveFrom(iar, ref state.RemoteEP);
//显示客户端地址和端口
Console.WriteLine("客户端终结点:{0}", state.RemoteEP.ToString());
//显示接收信息
Console.WriteLine("接收数据字节数:{0}", byteRead);
string message = Encoding.Default.GetString(state.Buffer, 0, byteRead);
Console.WriteLine("来着客户端信息:{0}", message);
//向客户端发送信息
SendMeaage(socket, state.RemoteEP, "成功接收!");
}
catch (Exception e)
{
Console.WriteLine("发生异常!异常信息:");
Console.WriteLine(e.Message);
}
finally
{
//非常重要:继续异步接收
socket.BeginReceiveFrom(
state.Buffer, 0, state.Buffer.Length,
SocketFlags.None,
ref state.RemoteEP,
EndReceiveFromCallback,
state);
}
}
/// <summary>
/// 向客户端发送信息
/// </summary>
/// <param name="socket">本地Socket(服务器Socket)</param>
/// <param name="remoteEndPoint">客户端终结点</param>
/// <param name="Message">信息</param>
static void SendMeaage(Socket socket, EndPoint remoteEndPoint, string Message)
{
byte[] bytes = Encoding.Default.GetBytes(Message);
socket.SendTo(bytes, remoteEndPoint);
}
}
/// <summary>
/// 用于异步接收处理的辅助类
/// </summary>
class State
{
public State(Socket socket)
{
this.Buffer = new byte[1024];
this.Socket = socket;
this.RemoteEP = new IPEndPoint(IPAddress.Any, 0);
}
/// <summary>
/// 获取本机(服务器)Socket
/// </summary>
public Socket Socket { get; private set; }
/// <summary>
/// 获取接收缓冲区
/// </summary>
public byte[] Buffer { get; private set; }
/// <summary>
/// 获取/设置客户端终结点
/// </summary>
public EndPoint RemoteEP;
}
}
UDP客户端
using System;using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleUdpClient
{
class Program
{
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
//客户端使用的终结点
EndPoint localEP = new IPEndPoint(IPAddress.Any, 0);
socket.Bind(localEP);
//启动异步接收
State state = new State(socket);
socket.BeginReceiveFrom(
state.Buffer, 0, state.Buffer.Length,
SocketFlags.None,
ref state.RemoteEP,
EndReceiveFromCallback,
state);
//向服务器发送信息
EndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8002);
SendMeaage(socket, remoteEP, "你好,这里是客户端,收到请回复!Over~~~~");
Console.ReadLine();
socket.Close();
}
//异步接收回调函数
static void EndReceiveFromCallback(IAsyncResult iar)
{
State state = iar.AsyncState as State;
Socket socket = state.Socket;
try
{
//完成接收
int byteRead = socket.EndReceiveFrom(iar, ref state.RemoteEP);
//显示服务器地址和端口
Console.WriteLine("服务器终结点:{0}", state.RemoteEP.ToString());
//显示接收信息
Console.WriteLine("接收数据字节数:{0}", byteRead);
string message = Encoding.Default.GetString(state.Buffer, 0, byteRead);
Console.WriteLine("来着服务器的信息:{0}", message);
}
catch (Exception e)
{
Console.WriteLine("发生异常!异常信息:");
Console.WriteLine(e.Message);
}
finally
{
//非常重要:继续异步接收
socket.BeginReceiveFrom(
state.Buffer, 0, state.Buffer.Length,
SocketFlags.None,
ref state.RemoteEP,
EndReceiveFromCallback,
state);
}
}
/// <summary>
/// 向服务器发送信息
/// </summary>
/// <param name="socket">本地Socket</param>
/// <param name="remoteEndPoint">服务器终结点</param>
/// <param name="Message">信息</param>
static void SendMeaage(Socket socket, EndPoint remoteEndPoint, string Message)
{
byte[] bytes = Encoding.Default.GetBytes(Message);
socket.SendTo(bytes, remoteEndPoint);
}
}
/// <summary>
/// 用于异步接收处理的辅助类
/// </summary>
class State
{
public State(Socket socket)
{
this.Buffer = new byte[1024];
this.Socket = socket;
this.RemoteEP = new IPEndPoint(IPAddress.Any, 0);
}
/// <summary>
/// 获取本机Socket
/// </summary>
public Socket Socket { get; private set; }
/// <summary>
/// 获取接收缓冲区
/// </summary>
public byte[] Buffer { get; private set; }
/// <summary>
/// 获取/设置客户端终结点
/// </summary>
public EndPoint RemoteEP;
}
}追问
谢谢你,写的比较完整;这个UDP是不是没有客户端和服务端之分吧?还有就是EndPoint localEP = new IPEndPoint(IPAddress.Any, 0); 0是不是端口号;这个应该别的程序也在使用这个端口的,为什么要使用0这个端口呢 有什么意义吗?谢谢
追答1)UDP是无连接通信,客户端和服务器区分不是很明显。
2)在 IPEndPoint 中,规定端口为 0 的意思是让.net 自己去寻址系统中可以使用的端口编号。
温馨提示:答案为网友推荐,仅供参考
第1个回答 推荐于2018-03-26
服务器端代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace AsyncServer
{
// 定义 UdpState类
public class UdpState
{
public UdpClient udpClient;
public IPEndPoint ipEndPoint;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public int counter = 0;
}
// 异步UDP类
public class AsyncUdpSever
{
// 定义节点
private IPEndPoint ipEndPoint = null;
private IPEndPoint remoteEP = null;
// 定义UDP发送和接收
private UdpClient udpReceive = null;
private UdpClient udpSend = null;
// 定义端口
private const int listenPort = 1100;
private const int remotePort = 1101;
UdpState udpReceiveState = null;
UdpState udpSendState = null;
// 异步状态同步
private ManualResetEvent sendDone = new ManualResetEvent(false);
private ManualResetEvent receiveDone = new ManualResetEvent(false);
public AsyncUdpSever()
{
// 本机节点
ipEndPoint = new IPEndPoint(IPAddress.Any, listenPort);
// 远程节点
remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0], remotePort);
// 实例化
udpReceive = new UdpClient(ipEndPoint);
udpSend = new UdpClient();
// 分别实例化udpSendState、udpReceiveState
udpReceiveState = new UdpState();
udpReceiveState.udpClient = udpReceive;
udpReceiveState.ipEndPoint = ipEndPoint;
udpSendState = new UdpState();
udpSendState.udpClient = udpSend;
udpSendState.ipEndPoint = remoteEP;
}
public void ReceiveMsg()
{
Console.WriteLine("listening for messages");
while (true)
{
lock (this)
{
// 调用接收回调函数
IAsyncResult iar = udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);
receiveDone.WaitOne();
Thread.Sleep(100);
}
}
}
// 接收回调函数
private void ReceiveCallback(IAsyncResult iar)
{
UdpState udpReceiveState = iar.AsyncState as UdpState;
if (iar.IsCompleted)
{
Byte[] receiveBytes = udpReceiveState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint);
string receiveString = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("Received: {0}", receiveString);
//Thread.Sleep(100);
receiveDone.Set();
SendMsg();
}
}
// 发送函数
private void SendMsg()
{
udpSend.Connect(udpSendState.ipEndPoint);
udpSendState.udpClient = udpSend;
udpSendState.counter++;
string message = string.Format("第{0}个UDP请求处理完成!", udpSendState.counter);
Byte[] sendBytes = Encoding.Unicode.GetBytes(message);
udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState);
sendDone.WaitOne();
}
// 发送回调函数
private void SendCallback(IAsyncResult iar)
{
UdpState udpState = iar.AsyncState as UdpState;
Console.WriteLine("第{0}个请求处理完毕!", udpState.counter);
Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar));
sendDone.Set();
}
// 主函数
public static void Main()
{
AsyncUdpSever aus = new AsyncUdpSever();
Thread t = new Thread(new ThreadStart(aus.ReceiveMsg));
t.Start();
Console.Read();
}
}
}
客户端代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace AsyncClient
{
// 定义 UdpState类
public class UdpState
{
public UdpClient udpClient = null;
public IPEndPoint ipEndPoint = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public int counter = 0;
}
// 异步UDP类
public class AsyncUdpClient
{
public static bool messageSent = false;
// Receive a message and write it to the console.
// 定义端口
private const int listenPort = 1101;
private const int remotePort = 1100;
// 定义节点
private IPEndPoint localEP = null;
private IPEndPoint remoteEP = null;
// 定义UDP发送和接收
private UdpClient udpReceive = null;
private UdpClient udpSend = null;
private UdpState udpSendState = null;
private UdpState udpReceiveState = null;
private int counter = 0;
// 异步状态同步
private ManualResetEvent sendDone = new ManualResetEvent(false);
private ManualResetEvent receiveDone = new ManualResetEvent(false);
// 定义套接字
//private Socket receiveSocket;
//private Socket sendSocket;
public AsyncUdpClient()
{
// 本机节点
localEP = new IPEndPoint(IPAddress.Any, listenPort);
// 远程节点
remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0], remotePort);
// 实例化
udpReceive = new UdpClient(localEP);
udpSend = new UdpClient();
// 分别实例化udpSendState、udpReceiveState
udpSendState = new UdpState();
udpSendState.ipEndPoint = remoteEP;
udpSendState.udpClient = udpSend;
udpReceiveState = new UdpState();
udpReceiveState.ipEndPoint = remoteEP;
udpReceiveState.udpClient = udpReceive;
//receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//receiveSocket.Bind(localEP);
//sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//sendSocket.Bind(remoteEP);
}
// 发送函数
public void SendMsg()
{
udpSend.Connect(remoteEP);
//Thread t = new Thread(new ThreadStart(ReceiveMessages));
//t.Start();
Byte[] sendBytes;
string message;
while (true)
{
message = "Client" + (counter++).ToString();
lock (this)
{
sendBytes = Encoding.ASCII.GetBytes(message);
udpSendState.counter = counter;
// 调用发送回调函数
udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState);
sendDone.WaitOne();
Thread.Sleep(200);
ReceiveMessages();
}
}
}
// 发送回调函数
public void SendCallback(IAsyncResult iar)
{
UdpState udpState = iar.AsyncState as UdpState;
if (iar.IsCompleted)
{
Console.WriteLine("第{0}个发送完毕!", udpState.counter);
Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar));
//if (udpState.counter == 10)
//{
// udpState.udpClient.Close();
//}
sendDone.Set();
}
}
// 接收函数
public void ReceiveMessages()
{
lock (this)
{
udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);
receiveDone.WaitOne();
Thread.Sleep(100);
}
}
// 接收回调函数
public void ReceiveCallback(IAsyncResult iar)
{
UdpState udpState = iar.AsyncState as UdpState;
if (iar.IsCompleted)
{
Byte[] receiveBytes = udpState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint);
string receiveString = Encoding.Unicode.GetString(receiveBytes);
Console.WriteLine("Received: {0}", receiveString);
receiveDone.Set();
}
}
// 主函数
public static void Main()
{
AsyncUdpClient auc = new AsyncUdpClient();
auc.SendMsg();
Console.Read();
}
}
}本回答被网友采纳
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace AsyncServer
{
// 定义 UdpState类
public class UdpState
{
public UdpClient udpClient;
public IPEndPoint ipEndPoint;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public int counter = 0;
}
// 异步UDP类
public class AsyncUdpSever
{
// 定义节点
private IPEndPoint ipEndPoint = null;
private IPEndPoint remoteEP = null;
// 定义UDP发送和接收
private UdpClient udpReceive = null;
private UdpClient udpSend = null;
// 定义端口
private const int listenPort = 1100;
private const int remotePort = 1101;
UdpState udpReceiveState = null;
UdpState udpSendState = null;
// 异步状态同步
private ManualResetEvent sendDone = new ManualResetEvent(false);
private ManualResetEvent receiveDone = new ManualResetEvent(false);
public AsyncUdpSever()
{
// 本机节点
ipEndPoint = new IPEndPoint(IPAddress.Any, listenPort);
// 远程节点
remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0], remotePort);
// 实例化
udpReceive = new UdpClient(ipEndPoint);
udpSend = new UdpClient();
// 分别实例化udpSendState、udpReceiveState
udpReceiveState = new UdpState();
udpReceiveState.udpClient = udpReceive;
udpReceiveState.ipEndPoint = ipEndPoint;
udpSendState = new UdpState();
udpSendState.udpClient = udpSend;
udpSendState.ipEndPoint = remoteEP;
}
public void ReceiveMsg()
{
Console.WriteLine("listening for messages");
while (true)
{
lock (this)
{
// 调用接收回调函数
IAsyncResult iar = udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);
receiveDone.WaitOne();
Thread.Sleep(100);
}
}
}
// 接收回调函数
private void ReceiveCallback(IAsyncResult iar)
{
UdpState udpReceiveState = iar.AsyncState as UdpState;
if (iar.IsCompleted)
{
Byte[] receiveBytes = udpReceiveState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint);
string receiveString = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("Received: {0}", receiveString);
//Thread.Sleep(100);
receiveDone.Set();
SendMsg();
}
}
// 发送函数
private void SendMsg()
{
udpSend.Connect(udpSendState.ipEndPoint);
udpSendState.udpClient = udpSend;
udpSendState.counter++;
string message = string.Format("第{0}个UDP请求处理完成!", udpSendState.counter);
Byte[] sendBytes = Encoding.Unicode.GetBytes(message);
udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState);
sendDone.WaitOne();
}
// 发送回调函数
private void SendCallback(IAsyncResult iar)
{
UdpState udpState = iar.AsyncState as UdpState;
Console.WriteLine("第{0}个请求处理完毕!", udpState.counter);
Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar));
sendDone.Set();
}
// 主函数
public static void Main()
{
AsyncUdpSever aus = new AsyncUdpSever();
Thread t = new Thread(new ThreadStart(aus.ReceiveMsg));
t.Start();
Console.Read();
}
}
}
客户端代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace AsyncClient
{
// 定义 UdpState类
public class UdpState
{
public UdpClient udpClient = null;
public IPEndPoint ipEndPoint = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public int counter = 0;
}
// 异步UDP类
public class AsyncUdpClient
{
public static bool messageSent = false;
// Receive a message and write it to the console.
// 定义端口
private const int listenPort = 1101;
private const int remotePort = 1100;
// 定义节点
private IPEndPoint localEP = null;
private IPEndPoint remoteEP = null;
// 定义UDP发送和接收
private UdpClient udpReceive = null;
private UdpClient udpSend = null;
private UdpState udpSendState = null;
private UdpState udpReceiveState = null;
private int counter = 0;
// 异步状态同步
private ManualResetEvent sendDone = new ManualResetEvent(false);
private ManualResetEvent receiveDone = new ManualResetEvent(false);
// 定义套接字
//private Socket receiveSocket;
//private Socket sendSocket;
public AsyncUdpClient()
{
// 本机节点
localEP = new IPEndPoint(IPAddress.Any, listenPort);
// 远程节点
remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0], remotePort);
// 实例化
udpReceive = new UdpClient(localEP);
udpSend = new UdpClient();
// 分别实例化udpSendState、udpReceiveState
udpSendState = new UdpState();
udpSendState.ipEndPoint = remoteEP;
udpSendState.udpClient = udpSend;
udpReceiveState = new UdpState();
udpReceiveState.ipEndPoint = remoteEP;
udpReceiveState.udpClient = udpReceive;
//receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//receiveSocket.Bind(localEP);
//sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//sendSocket.Bind(remoteEP);
}
// 发送函数
public void SendMsg()
{
udpSend.Connect(remoteEP);
//Thread t = new Thread(new ThreadStart(ReceiveMessages));
//t.Start();
Byte[] sendBytes;
string message;
while (true)
{
message = "Client" + (counter++).ToString();
lock (this)
{
sendBytes = Encoding.ASCII.GetBytes(message);
udpSendState.counter = counter;
// 调用发送回调函数
udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState);
sendDone.WaitOne();
Thread.Sleep(200);
ReceiveMessages();
}
}
}
// 发送回调函数
public void SendCallback(IAsyncResult iar)
{
UdpState udpState = iar.AsyncState as UdpState;
if (iar.IsCompleted)
{
Console.WriteLine("第{0}个发送完毕!", udpState.counter);
Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar));
//if (udpState.counter == 10)
//{
// udpState.udpClient.Close();
//}
sendDone.Set();
}
}
// 接收函数
public void ReceiveMessages()
{
lock (this)
{
udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);
receiveDone.WaitOne();
Thread.Sleep(100);
}
}
// 接收回调函数
public void ReceiveCallback(IAsyncResult iar)
{
UdpState udpState = iar.AsyncState as UdpState;
if (iar.IsCompleted)
{
Byte[] receiveBytes = udpState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint);
string receiveString = Encoding.Unicode.GetString(receiveBytes);
Console.WriteLine("Received: {0}", receiveString);
receiveDone.Set();
}
}
// 主函数
public static void Main()
{
AsyncUdpClient auc = new AsyncUdpClient();
auc.SendMsg();
Console.Read();
}
}
}本回答被网友采纳