本文整理汇总了C#中System.Net.Sockets.UdpClient.ReceiveAsync方法的典型用法代码示例。如果您正苦于以下问题:C# UdpClient.ReceiveAsync方法的具体用法?C# UdpClient.ReceiveAsync怎么用?C# UdpClient.ReceiveAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.UdpClient
的用法示例。
在下文中一共展示了UdpClient.ReceiveAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReceiveAndCheckAsync
private static async Task ReceiveAndCheckAsync(UdpClient client, string expectedMessage)
{
var incomingBytes = new List<byte>();
var connectionReset=false;
try
{
do
{
var udpReceiveResult = await client.ReceiveAsync();
incomingBytes.AddRange(udpReceiveResult.Buffer);
} while (TcpMessenger.IsReadingShouldContinue(incomingBytes));
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.ConnectionReset)
{
connectionReset = true;
}
}
var actual = Encoding.UTF8.GetString(incomingBytes.ToArray());
if (connectionReset)
{
TcpMessenger.ErrorConnectionReset(actual);
}
else if (actual != expectedMessage)
{
TcpMessenger.ErrorWrongMessage(actual);
}
}
示例2: BeginListeningAsync
public async Task BeginListeningAsync (CancellationToken token)
{
var client = new UdpClient (BroadcastEndpoint);
client.JoinMulticastGroup (BroadcastEndpoint.Address);
token.Register (() => client.Close ());
while (true) {
token.ThrowIfCancellationRequested ();
try {
var result = await client.ReceiveAsync ();
var data = Encoding.UTF8.GetString (result.Buffer);
if (data.StartsWith (Header, StringComparison.Ordinal)) {
if (ServerFound != null) {
var details = new ServerDetails {
Hostname = result.RemoteEndPoint.Address.ToString (),
Port = int.Parse (data.Substring (Header.Length))
};
LoggingService.LogInfo ("Found TunezServer at {0}", details.FullAddress);
ServerFound (this, details);
}
}
} catch (ObjectDisposedException) {
token.ThrowIfCancellationRequested ();
throw;
} catch (SocketException) {
token.ThrowIfCancellationRequested ();
// Ignore this
} catch (Exception ex) {
token.ThrowIfCancellationRequested ();
LoggingService.LogInfo ("Ignoring bad UDP {0}", ex);
}
}
}
示例3: ReaderAsync
private static async Task ReaderAsync(int port, string groupAddress)
{
using (var client = new UdpClient(port))
{
if (groupAddress != null)
{
client.JoinMulticastGroup(IPAddress.Parse(groupAddress));
WriteLine($"joining the multicast group {IPAddress.Parse(groupAddress)}");
}
bool completed = false;
do
{
WriteLine("starting the receiver");
UdpReceiveResult result = await client.ReceiveAsync();
byte[] datagram = result.Buffer;
string received = Encoding.UTF8.GetString(datagram);
WriteLine($"received {received}");
if (received == "bye")
{
completed = true;
}
} while (!completed);
WriteLine("receiver closing");
if (groupAddress != null)
{
client.DropMulticastGroup(IPAddress.Parse(groupAddress));
}
}
}
示例4: Receive
private void Receive(UdpClient udpClient)
{
udpClient.ReceiveAsync().ContinueWith(res =>
{
if (DataReceived != null)
DataReceived(res.Result.RemoteEndPoint, CommandBase.Parse(res.Result.Buffer));
Receive(udpClient);
});
}
示例5: StartUdpServer
private async void StartUdpServer()
{
var endPoint = new IPEndPoint(IPAddress.Any, 0);
var udp = new UdpClient(8080);
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<LogMessageHub>();
while (true)
{
UdpReceiveResult received = await udp.ReceiveAsync();
//TODO: Are we still listening for UDP messages at this point?
var buffer = received.Buffer;
var xmlText = Encoding.UTF8.GetString(buffer);
var logEvent = new LogEvent();
logEvent.PopulateFromLog4JXml(xmlText);
var json = logEvent.ToJson();
//This should be in the hub wrapper
var applicationId = logEvent.ApplicationId;
if (applicationId != null)
context.Clients.Group(applicationId).newLogMessage(json);
}
}
示例6: Start
public static async Task Start()
{
var client = new UdpClient(1812);
var serializer = new RadiusPacketSerializer();
while (true)
{
try
{
var result = await client.ReceiveAsync();
var request = serializer.Read(result.Buffer);
Console.WriteLine(request.Dump());
if (request.Code == RadiusPacketCode.AccessRequest)
{
var password = (RadiusBinaryAttribute)request.Attributes.FirstOrDefault(a => a.Type == RadiusAttributeType.UserPassword);
var code = ((password == null) || (string.Compare(RadiusPacketSerializer.DecodePassword(Secret, request.Authenticator, password.Value), Password, StringComparison.InvariantCulture) != 0))
? RadiusPacketCode.AccessReject
: RadiusPacketCode.AccessAccept;
var response = new RadiusPacket
{
Code = code,
Identifier = request.Identifier,
Authenticator = request.Authenticator
};
var buffer = serializer.Write(response);
await client.SendAsync(buffer, buffer.Length, result.RemoteEndPoint);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
示例7: GetServers
public async Task<IEnumerable<Server>> GetServers(
MasterServerRegion region = MasterServerRegion.All,
params MasterServerFilter[] masterServerFilters)
{
var servers = new List<Server>();
using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, 0)))
{
client.Connect(_steamSteamIpAddress, _steamSteamPort);
string thisServer = null;
while (thisServer != FIRST_AND_LAST_SERVER)
{
var requestPacket = CreateRequestPacket(thisServer ?? FIRST_AND_LAST_SERVER, region, masterServerFilters);
await client.SendAsync(requestPacket, requestPacket.Length);
var response = await client.ReceiveAsync();
var responseData = response.Buffer.ToList();
for (int i = HEADER_BYTES_LENGTH; i < responseData.Count; i++)
{
var ip = string.Join(".", responseData.GetRange(i, 4).ToArray());
int port = responseData[i + 4] << 8 | responseData[i + 5];
thisServer = string.Format("{0}:{1}", ip, port);
if (thisServer != FIRST_AND_LAST_SERVER)
{
servers.Add(new Server(new IPEndPoint(IPAddress.Parse(ip), port)));
}
i += 5;
}
}
}
return servers;
}
示例8: ReceiveBufferReaderAsync
public static async Task<BufferReader> ReceiveBufferReaderAsync(UdpClient client, int headerSize)
{
var response = await client.ReceiveAsync();
var reader = new BufferReader(response.Buffer);
reader.Skip(headerSize);
return reader;
}
示例9: receiveBytesAsync
public async Task<byte[]> receiveBytesAsync(int port)
{
UdpClient trasport = new UdpClient(port);
// IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
UdpReceiveResult result = await trasport.ReceiveAsync();
byte[] bytes = result.Buffer;
trasport.Close();
return bytes;
}
示例10: GetServerRules
public async Task<ServerRulesResult> GetServerRules()
{
using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, 0)))
{
client.Connect(EndPoint);
var requestPacket = new List<byte>();
requestPacket.AddRange(new Byte[] {0xFF, 0xFF, 0xFF, 0xFF, 0x56});
requestPacket.AddRange(BitConverter.GetBytes(-1));
await client.SendAsync(requestPacket.ToArray(), requestPacket.ToArray().Length);
UdpReceiveResult response = await client.ReceiveAsync();
List<byte> responseData = response.Buffer.ToList();
requestPacket.Clear();
requestPacket.AddRange(new Byte[] {0xFF, 0xFF, 0xFF, 0xFF, 0x56});
requestPacket.AddRange(responseData.GetRange(5, 4));
await client.SendAsync(requestPacket.ToArray(), requestPacket.ToArray().Length);
response = await client.ReceiveAsync();
return ServerRulesResult.Parse(response.Buffer);
}
}
示例11: ReceiveDataAsync
private async Task<ReceiveDataInfo> ReceiveDataAsync(ServerAddress address, byte[] data, CancellationToken ct, params char[] header)
{
var udpClient = new UdpClient();
var ipAddr = IPAddress.Parse(address.Ip);
try
{
udpClient.Connect(ipAddr, address.Port);
var sendTime = DateTime.Now;
await udpClient.SendAsync(data, data.Length);
Packet packet = null;
return await Task.Run(async () =>
{
while (true)
{
var clientResult = await udpClient.ReceiveAsync().WithCancellation(ct);
var remoteIp = clientResult.RemoteEndPoint.Address.ToString();
var remotePort = clientResult.RemoteEndPoint.Port;
var receiveDate = DateTime.Now;
var packetReader = new PacketReader(clientResult.Buffer);
var packetheader = packetReader.ReadLong();
if (packet == null)
{
packet = engineFactory.CreatePacket(packetheader);
}
packet.AddData(clientResult.Buffer);
if (packet.IsCompleted)
{
var messageReader = new PacketReader(packet.Payload);
var messageheader = messageReader.ReadByte();
var messageHeaderChar = Convert.ToChar(messageheader);
if (header.Contains(messageHeaderChar))
{
var result = new ReceiveDataInfo
{
Ping = (int)(DateTime.Now - sendTime).TotalMilliseconds,
Data = packet.Payload,
MessageHeaderChar = messageHeaderChar,
};
return result;
}
}
}
});
}
catch
{
throw new OperationCanceledException();
}
finally
{
udpClient.Close();
}
}
示例12: udpReceiveAsync
protected async void udpReceiveAsync(int port, HandleMessage handleMessage)
{
IPEndPoint remoteIP = new IPEndPoint(IPAddress.Any, port);
UdpClient udpClient = new UdpClient(remoteIP);
while (true)
{
UdpReceiveResult rst = await udpClient.ReceiveAsync();
handleMessage(Encoding.ASCII.GetString(rst.Buffer), rst.RemoteEndPoint.Address);
}
}
示例13: ServeAsync
public static async Task ServeAsync(UdpClient server)
{
IDictionary<IPEndPoint, List<byte>> received=new Dictionary<IPEndPoint, List<byte>>();
var sendTasks = new List<Task>();
while (_sent < Constants.ClientCount)
{
await server.ReceiveAsync()
.ContinueWith(udpReceivedResult => sendTasks.Add(AddReceivedToDicAndSendIfShouldAsync(server, udpReceivedResult.Result, received)));
}
await Task.WhenAll(sendTasks);
}
示例14: SendToClientFileAsync
/// <summary>
/// 向客户端异步发送文件
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
/// <param name="filePath"></param>
public async Task SendToClientFileAsync(string ip, int port, string filePath, Message msg)
{
// 新建 Udp 用于发送文件
var sendClient = new UdpClient();
try
{
FileInfo fileInfo = new FileInfo(filePath);
msg.Type = MessageEnum.FILE; // 设置发送文件标识
msg.FileLength = fileInfo.Length;
msg.FileName = Regex.Match(filePath, @"\\([^\\]+\.[^\\]+)").Groups[1].Value; // 获取文件名
byte[] datagram = Encoding.Unicode.GetBytes(JsonConvert.SerializeObject(msg));
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
/*
* 向‘原’远程客户端发送请求传送文件的请求,
* 接收‘新’远程客户端的响应,获取传送文件的端口
*
* 注:原远程客户端用于发送消息,新远程客户端用于发送文件
*/
await sendClient.SendAsync(datagram, datagram.Length, endPoint);
//IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
UdpReceiveResult result = await sendClient.ReceiveAsync().ConfigureAwait(false); // 阻塞直到接收到远程客户端的响应
/*
* 开始发送文件
*/
byte[] buffer = new byte[MAXSIZE];
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 1, true))
{
int percent = 0;
int count = 0;
while ((count = await fs.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
{
//await Task.Delay(10);
await sendClient.SendAsync(buffer, count, result.RemoteEndPoint);
if (Client.SendFileProgressNotify != null)
{
Client.SendFileProgressNotify(String.Format("{0:F2}%", (percent += count) / msg.FileLength * 100));
}
}
sendClient.Close();
}
}
catch (Exception e)
{
Log.Write(e.Message);
}
}
示例15: ServerAsync
static async Task ServerAsync(CancellationToken ct)
{
throw new ApplicationException("died");
var client = new UdpClient(5555);
var request = new byte[0];
while (!ct.IsCancellationRequested)
{
await client.SendAsync(request, request.Length);
var response = await client.ReceiveAsync();
}
}