本文整理汇总了C#中System.Net.Sockets.Socket.ReceiveFromAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.ReceiveFromAsync方法的具体用法?C# Socket.ReceiveFromAsync怎么用?C# Socket.ReceiveFromAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.ReceiveFromAsync方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Start
/// <summary>
/// Starts to listen
/// </summary>
/// <param name="config">The server config.</param>
/// <returns></returns>
public override bool Start(IServerConfig config)
{
try
{
m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
m_ListenSocket.Bind(this.EndPoint);
uint IOC_IN = 0x80000000;
uint IOC_VENDOR = 0x18000000;
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
byte[] optionInValue = { Convert.ToByte(false) };
byte[] optionOutValue = new byte[4];
m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);
var eventArgs = new SocketAsyncEventArgs();
eventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(eventArgs_Completed);
eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
int receiveBufferSize = config.ReceiveBufferSize <= 0 ? 2048 : config.ReceiveBufferSize;
var buffer = new byte[receiveBufferSize];
eventArgs.SetBuffer(buffer, 0, buffer.Length);
m_ListenSocket.ReceiveFromAsync(eventArgs);
return true;
}
catch (Exception e)
{
OnError(e);
return false;
}
}
示例2: Start
/// <summary>
/// Starts to listen
/// </summary>
/// <param name="config">The server config.</param>
/// <returns></returns>
public override bool Start(IServerConfig config)
{
try
{
m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
m_ListenSocket.Bind(this.EndPoint);
//Mono doesn't support it
if (Platform.SupportSocketIOControlByCodeEnum)
{
uint IOC_IN = 0x80000000;
uint IOC_VENDOR = 0x18000000;
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
byte[] optionInValue = { Convert.ToByte(false) };
byte[] optionOutValue = new byte[4];
m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);
}
var eventArgs = m_SaePool.Get();
m_ListenSocket.ReceiveFromAsync(eventArgs);
return true;
}
catch (Exception e)
{
OnError(e);
return false;
}
}
示例3: UdpCommunication
/// <summary>
/// Create a UdpCommunication object using an existing Socket.
/// </summary>
public UdpCommunication(Socket socket, IPEndPoint endPoint)
{
_socket = socket;
_endPoint = endPoint;
// Start asynchronous read
try
{
_receiveArgs = new SocketAsyncEventArgs();
_receiveArgs.UserToken = _socket;
_receiveArgs.RemoteEndPoint = _endPoint;
_readBuffer = new byte[READBUFFERSIZE];
_receiveArgs.SetBuffer(_readBuffer, 0, _readBuffer.Length);
_receiveArgs.Completed += new EventHandler<SocketAsyncEventArgs>(_socket_ReceivedData);
if (_socket.ReceiveFromAsync(_receiveArgs) == false) // Returns true if the I/O operation is pending. Returns false if the I/O operation completed synchronously and the SocketAsyncEventArgs.Completed event will not be raised.
_socket_ReceivedData(_socket, _receiveArgs);
}
catch (Exception ex)
{
// On failure free up the SocketAsyncEventArgs
if (_receiveArgs != null)
{
_receiveArgs.Completed -= new EventHandler<SocketAsyncEventArgs>(_socket_ReceivedData);
_receiveArgs.Dispose();
_receiveArgs = null;
}
throw;
}
}
示例4: Start
/// <summary>
/// Starts to listen
/// </summary>
/// <param name="config">The server config.</param>
/// <returns></returns>
public override bool Start(IServerConfig config)
{
SaeState saeState = null;
try
{
m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
m_ListenSocket.Bind(this.EndPoint);
//Mono doesn't support it
if (Platform.SupportSocketIOControlByCodeEnum)
{
uint IOC_IN = 0x80000000;
uint IOC_VENDOR = 0x18000000;
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
byte[] optionInValue = { Convert.ToByte(false) };
byte[] optionOutValue = new byte[4];
m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);
}
saeState = m_SaePool.Get();
var sae = saeState.Sae;
sae.UserToken = saeState;
sae.RemoteEndPoint = m_AnyEndPoint;
sae.Completed += new EventHandler<SocketAsyncEventArgs>(eventArgs_Completed);
if (!m_ListenSocket.ReceiveFromAsync(sae))
eventArgs_Completed(this, sae);
return true;
}
catch (Exception e)
{
if (saeState != null)
{
saeState.Sae.Completed -= new EventHandler<SocketAsyncEventArgs>(eventArgs_Completed);
m_SaePool.Return(saeState);
}
OnError(e);
return false;
}
}
示例5: ConnectToSimConnect
public void ConnectToSimConnect()
{
try
{
sc = new SimConnect("VE_SC_WPF", (IntPtr)0, 0, scReady, 0);
sc.OnRecvClientData += sc_OnRecvClientData;
sc.OnRecvCustomAction += sc_OnRecvCustomAction;
sc.OnRecvEvent += sc_OnRecvEvent;
sc.OnRecvEventFilename += sc_OnRecvEventFilename;
sc.OnRecvEventFrame += sc_OnRecvEventFrame;
sc.OnRecvEventObjectAddremove += sc_OnRecvEventObjectAddremove;
sc.OnRecvException += sc_OnRecvException;
sc.OnRecvGroundInfo += sc_OnRecvGroundInfo;
sc.OnRecvNull += sc_OnRecvNull;
sc.OnRecvObserverData += sc_OnRecvObserverData;
sc.OnRecvOpen += sc_OnRecvOpen;
sc.OnRecvQuit += sc_OnRecvQuit;
sc.OnRecvSimobjectData += sc_OnRecvSimobjectData;
sc.OnRecvSimobjectDataBytype += sc_OnRecvSimobjectDataBytype;
sc.OnRecvSynchronousBlock += sc_OnRecvSynchronousBlock;
sc.OnRecvSystemState += sc_OnRecvSystemState;
_udpRecv = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_udpRecv.Bind(new IPEndPoint(IPAddress.Any, 49000));
SocketAsyncEventArgs e = new SocketAsyncEventArgs();
e.Completed += OnReceive;
e.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
e.SetBuffer(new byte[255], 0, 255);
if (!_udpRecv.ReceiveFromAsync(e))
OnReceive(_udpRecv, e);
}
catch (COMException)
{
Console.WriteLine("Unable to connect to SimConnect");
}
catch (Exception)
{
}
finally
{
}
bgThread = new Thread(new ThreadStart(scMessageThread));
bgThread.IsBackground = true;
bgThread.Start();
}
示例6: SendIcmpEchoRequestOverRawSocket
private async Task<PingReply> SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
EndPoint endPoint = new IPEndPoint(address, 0);
bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork;
ProtocolType protocolType = isIpv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6;
// Use the current thread's ID as the identifier.
ushort identifier = (ushort)Environment.CurrentManagedThreadId;
IcmpHeader header = new IcmpHeader()
{
Type = isIpv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest,
Code = 0,
HeaderChecksum = 0,
Identifier = identifier,
SequenceNumber = 0,
};
byte[] sendBuffer = CreateSendMessageBuffer(header, buffer);
using (Socket socket = new Socket(address.AddressFamily, SocketType.Raw, protocolType))
{
socket.ReceiveTimeout = timeout;
socket.SendTimeout = timeout;
// Setting Socket.DontFragment and .Ttl is not supported on Unix, so ignore the PingOptions parameter.
int ipHeaderLength = isIpv4 ? IpHeaderLengthInBytes : 0;
await socket.SendToAsync(new ArraySegment<byte>(sendBuffer), SocketFlags.None, endPoint).ConfigureAwait(false);
byte[] receiveBuffer = new byte[ipHeaderLength + IcmpHeaderLengthInBytes + buffer.Length];
long elapsed;
Stopwatch sw = Stopwatch.StartNew();
// Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response
// to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout.
// For example, when pinging the local host, we need to filter out our own echo requests that the socket reads.
while ((elapsed = sw.ElapsedMilliseconds) < timeout)
{
Task<SocketReceiveFromResult> receiveTask = socket.ReceiveFromAsync(
new ArraySegment<byte>(receiveBuffer),
SocketFlags.None,
endPoint);
var cts = new CancellationTokenSource();
Task finished = await Task.WhenAny(receiveTask, Task.Delay(timeout - (int)elapsed, cts.Token)).ConfigureAwait(false);
cts.Cancel();
if (finished != receiveTask)
{
sw.Stop();
return CreateTimedOutPingReply();
}
SocketReceiveFromResult receiveResult = receiveTask.GetAwaiter().GetResult();
int bytesReceived = receiveResult.ReceivedBytes;
if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes)
{
continue; // Not enough bytes to reconstruct IP header + ICMP header.
}
byte type, code;
unsafe
{
fixed (byte* bytesPtr = receiveBuffer)
{
int icmpHeaderOffset = ipHeaderLength;
IcmpHeader receivedHeader = *((IcmpHeader*)(bytesPtr + icmpHeaderOffset)); // Skip IP header.
type = receivedHeader.Type;
code = receivedHeader.Code;
if (identifier != receivedHeader.Identifier
|| type == (byte)IcmpV4MessageType.EchoRequest
|| type == (byte)IcmpV6MessageType.EchoRequest) // Echo Request, ignore
{
continue;
}
}
}
sw.Stop();
long roundTripTime = sw.ElapsedMilliseconds;
int dataOffset = ipHeaderLength + IcmpHeaderLengthInBytes;
// We want to return a buffer with the actual data we sent out, not including the header data.
byte[] dataBuffer = new byte[bytesReceived - dataOffset];
Array.Copy(receiveBuffer, dataOffset, dataBuffer, 0, dataBuffer.Length);
IPStatus status = isIpv4
? IcmpV4MessageConstants.MapV4TypeToIPStatus(type, code)
: IcmpV6MessageConstants.MapV6TypeToIPStatus(type, code);
return new PingReply(address, options, status, roundTripTime, dataBuffer);
}
// We have exceeded our timeout duration, and no reply has been received.
sw.Stop();
return CreateTimedOutPingReply();
}
}
示例7: UdpRecieve
internal static byte[] UdpRecieve(Socket s, ref IPEndPoint EP)
{
string response = "Operation Timeout";
byte[] msg = null;
if (s != null)
{
// Create SocketAsyncEventArgs context object
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = EP;
// Setup the buffer to receive the data
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
// Inline event handler for the Completed event.
// Note: This even handler was implemented inline in order to make this method self-contained.
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object ss, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Retrieve the data from the buffer
msg = new byte[e.BytesTransferred];
Array.Copy(e.Buffer, e.Offset, msg, 0, e.BytesTransferred);
}
else
{
response = e.SocketError.ToString();
}
try
{
_clientDone[s].Set();
}
catch (KeyNotFoundException)
{
}
});
// Sets the state of the event to nonsignaled, causing threads to block
_clientDone[s].Reset();
// Make an asynchronous Receive request over the socket
if (s.ReceiveFromAsync(socketEventArg) == false)
{
if (socketEventArg.SocketError == SocketError.Success)
{
// Retrieve the data from the buffer
msg = new byte[socketEventArg.BytesTransferred];
Array.Copy(socketEventArg.Buffer, socketEventArg.Offset, msg, 0, socketEventArg.BytesTransferred);
}
else
{
response = socketEventArg.SocketError.ToString();
}
try
{
_clientDone[s].Set();
}
catch (KeyNotFoundException)
{
}
}
// Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
// If no response comes back within this time then proceed
_clientDone[s].WaitOne();//(TimeOut);
}
return msg;
}
示例8: StartReceive
private void StartReceive (Socket socket, SocketAsyncEventArgs args, BufferValueReader reader)
{
if (!this.running)
return;
Interlocked.Increment (ref this.pendingAsync);
try
{
args.SetBuffer (0, args.Buffer.Length);
while (!socket.ReceiveFromAsync (args))
Receive (this, args);
}
catch (ObjectDisposedException) // Socket is disposed, we're done.
{
Interlocked.Decrement (ref this.pendingAsync);
}
}
示例9: CreateAsyncEventArgs
private SocketAsyncEventArgs CreateAsyncEventArgs(Socket socket, byte[] receiveBuffer)
{
var args = new SocketAsyncEventArgs();
args.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
args.RemoteEndPoint = new IPEndPoint((socket.AddressFamily == AddressFamily.InterNetworkV6) ? IPAddress.IPv6None : IPAddress.None, 0);
args.Completed += m_asyncEventArgs_Completed;
if (!socket.ReceiveFromAsync(args))
{
m_asyncEventArgs_Completed(socket, args);
}
return args;
}
示例10: StartReceive
private void StartReceive(Socket socket)
{
SocketAsyncEventArgs parameters = new SocketAsyncEventArgs();
if (socket.AddressFamily == AddressFamily.InterNetwork)
parameters.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
else
parameters.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
parameters.Completed += new EventHandler<SocketAsyncEventArgs>(ReceiveCallback);
parameters.SetBuffer(new byte[4096], 0, 4096);
socket.ReceiveFromAsync(parameters);
}
示例11: SetupUDPRecv
private void SetupUDPRecv()
{
// setup receiver
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 49005);
SimulatorRECV = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
SimulatorRECV.Bind(ipep);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
recvargs.RemoteEndPoint = sender;
recvargs.SetBuffer(udpdata, 0, udpdata.Length);
SimulatorRECV.ReceiveFromAsync(recvargs);
}
示例12: open
protected override void open()
{
if (_socket == null || _socket.Connected == false)
{
System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " %%%%%%%%%%%%%%%%%% UdpCommunication.Open. Attempting to connect to " + _udpHostName + ":" + _udpPort + ".");
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // interNetwork is IPv4
// Get the end point to send data to.
IPAddress ipAddress;
if (System.Net.IPAddress.TryParse(_udpHostName, out ipAddress) == false)
ipAddress = Dns.GetHostEntry(_udpHostName).AddressList[0];
_endPoint = new IPEndPoint(ipAddress, _udpPort);
IPEndPoint bindingEndPoint = null;
if (IPAddress.Broadcast.Equals(_endPoint.Address))
{
string localHostName = System.Net.Dns.GetHostName();
IPAddress[] ipAddresses = Dns.GetHostEntry(localHostName).AddressList;
foreach (IPAddress ip in ipAddresses)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
bindingEndPoint = new IPEndPoint(ip, _udpPort); // This needs to be a local ip address, and the port to listen on.
break;
}
}
if (bindingEndPoint == null)
throw new Exception("There is no outside ip address for this machine.");
_socket.EnableBroadcast = true;
}
else
{
//IPEndPoint bindingEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), _udpPort);
bindingEndPoint = new IPEndPoint(IPAddress.Any, _udpPort); // This needs to be a local ip address, and the port to listen on.
}
_socket.Bind(bindingEndPoint);
// Start listening
_receiveArgs = new SocketAsyncEventArgs();
try
{
_receiveArgs.UserToken = _socket;
_receiveArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0); // it doesn't appear to matter what address or port you set this to it just needs to be set to something.
_readBuffer = new byte[READBUFFERSIZE];
_receiveArgs.SetBuffer(_readBuffer, 0, _readBuffer.Length);
_receiveArgs.Completed += new EventHandler<SocketAsyncEventArgs>(_socket_ReceivedData);
if (_socket.ReceiveFromAsync(_receiveArgs) == false) // Returns true if the I/O operation is pending. Returns false if the I/O operation completed synchronously and the SocketAsyncEventArgs.Completed event will not be raised.
_socket_ReceivedData(_socket, _receiveArgs);
}
catch
{
// On failure free up the SocketAsyncEventArgs
if (_receiveArgs != null)
{
_receiveArgs.Completed -= new EventHandler<SocketAsyncEventArgs>(_socket_ReceivedData);
_receiveArgs.Dispose();
_receiveArgs = null;
}
throw;
}
}
}