本文整理汇总了C#中System.Net.Sockets.Socket.EndReceiveFrom方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.EndReceiveFrom方法的具体用法?C# Socket.EndReceiveFrom怎么用?C# Socket.EndReceiveFrom使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.EndReceiveFrom方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: StartUdpServer
private async void StartUdpServer()
{
var udpListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
// Important to specify a timeout value, otherwise the socket ReceiveFrom()
// will block indefinitely if no packets are received and the thread will never terminate
udpListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100);
udpListener.Bind(new IPEndPoint(IPAddress.Any, 54321));
var buffer = new byte[1500];
EndPoint sender = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
var result = await Task.Factory.FromAsync(
(iar, s) =>
udpListener.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref sender, iar,
null),
iar => udpListener.EndReceiveFrom(iar, ref sender), null);
if (result > 0)
{
if (firstPacket == DateTime.MinValue)
firstPacket = DateTime.Now;
var data = new byte[result];
Buffer.BlockCopy(buffer, 0, data, 0, result);
ring.AddData(data);
Frame f = null;
do
{
f = ring.ReadFrame();
if (f != null)
{
f.Time = (DateTime.Now - firstPacket).TotalSeconds;
var ev = OnFrameReceived;
if (ev != null)
{
OnFrameReceived(this, new FrameReceivedEventArgs(f));
}
}
} while (f != null);
}
}
}
示例2: Receive
private void Receive(Socket socket, EndPoint endPoint)
{
var data = new byte[socket.ReceiveBufferSize];
socket.BeginReceiveFrom(data, 0, data.Length, SocketFlags.None, ref endPoint, ar =>
{
if (DataReceived != null)
{
var i = socket.EndReceiveFrom(ar, ref endPoint);
var data2 = new byte[i];
Array.Copy(data, data2, i);
var command = CommandBase.Parse(data2);
if (_debugLog != null)
_debugLog.WriteLine("Receive " + command.GetType().Name + " Token: " + command.Token);
DataReceived(command);
}
Receive(socket, endPoint);
}, null);
}
示例3: EndReceive
FramingData EndReceive(Socket listenSocket, IAsyncResult result)
{
// if we've started the shutdown process, then we've disposed
// the socket and calls to socket.EndReceive will throw
if (closed)
return null;
byte[] buffer = ((SocketReceiveState)result.AsyncState).Buffer;
Debug.Assert(buffer != null);
FramingData data = null;
try
{
int count = 0;
lock (ThisLock)
{
// if we've started the shutdown process, socket is disposed
// and calls to socket.EndReceive will throw
if (!closed)
{
EndPoint dummy = CreateDummyEndPoint(listenSocket);
count = listenSocket.EndReceiveFrom(result, ref dummy);
}
}
if (count > 0)
{
data = FramingCodec.Decode(new ArraySegment<byte>(buffer, 0, count));
}
}
catch (Exception e)
{
Debug.WriteLine("Error in completing the async receive via EndReceiveFrom method.");
Debug.WriteLine(e.ToString());
}
finally
{
if (data == null)
{
this.bufferManager.ReturnBuffer(buffer);
buffer = null;
}
}
return data;
}
示例4: NetworkTargetUdpTest
public void NetworkTargetUdpTest()
{
var target = new NetworkTarget()
{
Address = "udp://127.0.0.1:3002",
Layout = "${message}\n",
KeepConnection = true,
};
string expectedResult = string.Empty;
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
Exception receiveException = null;
var receivedMessages = new List<string>();
var receiveFinished = new ManualResetEvent(false);
byte[] receiveBuffer = new byte[4096];
listener.Bind(new IPEndPoint(IPAddress.Loopback, 3002));
EndPoint remoteEndPoint = null;
AsyncCallback receivedDatagram = null;
receivedDatagram = result =>
{
try
{
int got = listener.EndReceiveFrom(result, ref remoteEndPoint);
string message = Encoding.UTF8.GetString(receiveBuffer, 0, got);
lock (receivedMessages)
{
receivedMessages.Add(message);
if (receivedMessages.Count == 100)
{
receiveFinished.Set();
}
}
remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null);
}
catch (Exception ex)
{
receiveException = ex;
}
};
remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null);
target.Initialize(new LoggingConfiguration());
int pendingWrites = 100;
var writeCompleted = new ManualResetEvent(false);
var exceptions = new List<Exception>();
AsyncContinuation writeFinished =
ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
pendingWrites--;
if (pendingWrites == 0)
{
writeCompleted.Set();
}
}
};
int toWrite = pendingWrites;
for (int i = 0; i < toWrite; ++i)
{
var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished);
target.WriteAsyncLogEvent(ev);
expectedResult += "message" + i + "\n";
}
Assert.IsTrue(writeCompleted.WaitOne(30000, false));
target.Close();
Assert.IsTrue(receiveFinished.WaitOne(30000, false));
Assert.AreEqual(toWrite, receivedMessages.Count);
for (int i = 0; i < toWrite; ++i)
{
Assert.IsTrue(receivedMessages.Contains("message" + i + "\n"), "Message #" + i + " not received.");
}
Assert.IsNull(receiveException, "Receive exception: " + receiveException);
}
}
示例5: ReceiveCallback
////廣播3
private void ReceiveCallback(IAsyncResult iar)
{
EndPoint remoteEnd = new IPEndPoint(IPAddress.Any, Int32.Parse(control.udp_port));
sock = (Socket)iar.AsyncState;
int received = sock.EndReceiveFrom(iar, ref remoteEnd);
byte[] localMsg = new byte[received];
Array.Copy(getdata, localMsg, received);
var input = Encoding.UTF8.GetString(localMsg, 0, received);
var inn = "UDP=" + input;
_logger.Info(inn);
input = input.Replace("\a", "");
input = input.Replace("\r\n", string.Empty);
analysis_type(input);
sock.BeginReceiveFrom(getdata, 0, getdata.Length, SocketFlags.None, ref remoteEnd, new AsyncCallback(ReceiveCallback), sock);
}
示例6: _Receive
private void _Receive(Socket Socket, byte[] Buffer)
{
while (true)
{
try
{
const int offset = 0;
EndPoint endpoint = new IPEndPoint(Socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
Socket.BeginReceiveFrom(Buffer, offset, Buffer.Length, SocketFlags.None, ref endpoint, delegate(IAsyncResult ar)
{
try
{
int size = Socket.EndReceiveFrom(ar, ref endpoint);
if (this.Received != null)
{
this.Received((IPEndPoint)endpoint, new BufferData(Buffer).GetPartion(0, size));
}
}
catch (SocketException se)
{
if (!_CanIgnore(se))
{
throw se;
}
}
// Restart receive cycle
this._Receive(Socket, Buffer);
}, null);
return;
}
catch (SocketException se)
{
if (!_CanIgnore(se))
{
throw se;
}
}
}
}