本文整理汇总了C#中System.Net.Sockets.Socket.SendToAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.SendToAsync方法的具体用法?C# Socket.SendToAsync怎么用?C# Socket.SendToAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.SendToAsync方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendState
public void SendState(X360State state)
{
byte[] data = state.GetState();
if (null != this.netduinoPlusAddress)
{
Debug.WriteLine("Sending:" + state.ToString());
#if WINDOWS
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
SocketAsyncEventArgs socketArgs = new SocketAsyncEventArgs();
socketArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(this.netduinoPlusAddress), 9999);
socketArgs.SetBuffer(data, 0, data.Length);
socketArgs.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) { });
socket.SendToAsync(socketArgs);
#endif
}
else
{
#if WINDOWS
try
{
if ((false == IsTheSame(data)) || (null == this.port))
{
if (null == this.port)
{
if (this.framesToIgnore-- <= 0)
{
// if (Array.Exists<String>(SerialPort.GetPortNames(), s => s == this.portName))
{
this.port = new SerialPort(this.portName, 115200/* this.config.ArduinoPortBaud*/, Parity.None, 8, StopBits.One);
this.port.DataReceived += this.DataReceived;
this.port.Open();
Thread.Sleep(2000); // wait for bloody arduino nano.
}
}
}
if (null != this.port)
{
this.port.Write(data, 0, data.Length);
this.lastState = data;
}
}
}
catch (Exception ex)
{
this.port = null;
Debug.WriteLine(ex.Message);
this.framesToIgnore = 60; // too lazy to do some tread sleep magic.
}
#endif
}
}
示例2: Send
// There's no MiLight controller package yet, so let's just inline the
// socket code here...
private void Send(byte[] command)
{
// We should be able to use UdpClient. Gah.
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
var args = new SocketAsyncEventArgs { RemoteEndPoint = endPoint };
args.SetBuffer(command, 0, command.Length);
using (var done = new ManualResetEvent(false))
{
args.Completed += (sender, e) => done.Set();
if (!socket.SendToAsync(args))
{
throw new Exception("Failed to send to lighting host");
}
if (!done.WaitOne(TimeSpan.FromSeconds(5)))
{
throw new Exception("Timed out sending to lighting host");
}
}
}
}
示例3: 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();
}
}
示例4: SendUdp
internal static int SendUdp(Socket s, byte[] msg, int len, IPEndPoint EP)
{
string response = "Operation Timeout";
int sent = 0;
if (s != null)
{
// Create SocketAsyncEventArgs context object
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
// Set properties on context object
socketEventArg.RemoteEndPoint = EP;
// Inline event handler for the Completed event.
// Note: This event handler was implemented inline in order to make this method self-contained.
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object ss, SocketAsyncEventArgs e)
{
response = e.SocketError.ToString();
sent = e.BytesTransferred;
// Unblock the UI thread
try
{
_clientDone[s].Set();
}
catch (KeyNotFoundException)
{
}
});
// Add the data to be sent into the buffer
socketEventArg.SetBuffer(msg, 0, len);
// Sets the state of the event to nonsignaled, causing threads to block
_clientDone[s].Reset();
// Make an asynchronous Send request over the socket
if (s.SendToAsync(socketEventArg) == false)
{
response = socketEventArg.SocketError.ToString();
sent = socketEventArg.BytesTransferred;
// Unblock the UI thread
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 sent;
}
示例5: DeterminePort
public void DeterminePort(AsyncCallback callback)
{
if (PortDetermined)
return;
acb = new AsyncCallback(callback);
RtpEvntArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(PortDetermineServerAddress), PortDetermineServerPort);
var send_buffer = Encoding.UTF8.GetBytes("Connect;LoopBack;");
RtpEvntArgs.SetBuffer(send_buffer, 0, send_buffer.Length);
CurrentState = RtpState.DeterminePort;
try
{
RtpSocket.SendToAsync(RtpEvntArgs);
}
catch (ObjectDisposedException)
{
RtpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
RtpSocket.SendToAsync(RtpEvntArgs);
}
}
示例6: SentWorker
private bool SentWorker( Socket s, SocketAsyncEventArgs b )
{
var index = (int) b.UserToken;
var isStream = s.SocketType == SocketType.Stream;
if (isStream){
while (
this._isAttacking
&& this._sendLast[ index ]-- > 0
&& ( b.SocketError == SocketError.Success && s.Connected ) )
try {
//this.RefreshSendData( index );
if ( s.SendAsync( this._sendArgs[ index ] ) ) return true;
}
catch { }
}
else {
while ( this._isAttacking ) {
try {
if ( s.SendToAsync( this._sendArgs[ index ] ) ) return true; //prevent stack overflow
}
catch { }
}
}
return !this._isAttacking && b.SocketError == SocketError.Success;
}
示例7: IsIoCompletionPortsSupported
/// <summary>
/// Gets if IO completion ports supported by OS.
/// </summary>
/// <returns></returns>
public static bool IsIoCompletionPortsSupported()
{
Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
try{
SocketAsyncEventArgs e = new SocketAsyncEventArgs();
e.SetBuffer(new byte[0],0,0);
e.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback,111);
s.SendToAsync(e);
return true;
}
catch(NotSupportedException nX){
string dummy = nX.Message;
return false;
}
finally{
s.Close();
}
}
示例8: SendUDP
//
// Send a command over UDP
//
public static void SendUDP(object sender, DoWorkEventArgs ea)
{
const int MAX_RECVBUFFER_SIZE = 2048;
// Create a new socket instance
// Since this socket is only used within the WiFi network, the preference is on the NonCellular side,
// to not send the UDP broadcast into the Internet, it wouldn't be delivered...
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetNetworkPreference(NetworkSelectionCharacteristics.NonCellular);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
// Let's assume that the local network broadcast address can be created by changing the last digit to 255
// - Like 192.168.0.xx -> 192.168.0.255
// WP8 does support sending to IPAddress.Broadcast, i.e. "255.255.255.255", but there's something
// wrong with the socket handling:
// - Cannot use 'SendToAsync', but have to use 'ConnectAsync' instead
// - Cannot receive any data using the same socket (code seems OK, but nothing is received)
byte[] localBroadcastAddressBytes = FindMyIPAddress().GetAddressBytes();
localBroadcastAddressBytes[3] = 255;
IPAddress localBroadcast = new IPAddress(localBroadcastAddressBytes);
socketEventArg.RemoteEndPoint = new IPEndPoint(localBroadcast, UDPPort);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
switch (e.LastOperation)
{
case SocketAsyncOperation.SendTo: // The broadcast was sent successfully, now start listening on the same socket
Socket sock = e.UserToken as Socket;
socketEventArg.SetBuffer(new Byte[MAX_RECVBUFFER_SIZE], 0, MAX_RECVBUFFER_SIZE);
sock.ReceiveFromAsync(socketEventArg);
break;
case SocketAsyncOperation.ReceiveFrom: // Received a response to the broadcast
if (e.SocketError == System.Net.Sockets.SocketError.Success)
{
// Retrieve the data from the buffer
var response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response = response.Trim('\0');
System.Diagnostics.Debug.WriteLine("Received JSON data: " + response);
// Is this is an 'identify' or 'command' response?
HeatPumpIdentifyResponse identifyResponse = (HeatPumpIdentifyResponse)JsonFunctions.DeserializeFromStringToJson(response, typeof(HeatPumpIdentifyResponse));
System.Diagnostics.Debug.WriteLine("Response to command: " + identifyResponse.command + ": " + response);
// Run the notification handler (if found)
if (App.ViewModel.notificationHandlers.ContainsKey(identifyResponse.command))
{
System.Diagnostics.Debug.WriteLine("Found handler for command " + identifyResponse.command);
App.ViewModel.notificationHandlers[identifyResponse.command](response);
}
}
break;
}
});
// Add the data to be sent into the send buffer
byte[] payload = Encoding.UTF8.GetBytes((string)ea.Argument);
socketEventArg.SetBuffer(payload, 0, payload.Length);
// Add the socket as the UserToken for use within the event handler
socketEventArg.UserToken = socket;
// Send the UDP broadcast
socket.SendToAsync(socketEventArg);
}
示例9: Search
//.........这里部分代码省略.........
{
try
{
socket.ReceiveBufferSize = RESULT_BUFFER;
socket.ReceiveAsync(rcv_event_args);
}
catch (ObjectDisposedException)
{
Log("Socket is already disposed.");
}
}
});
snd_event_args.Completed += SND_Handler;
var RCV_Handler = new EventHandler<SocketAsyncEventArgs>((sender, e) =>
{
if (e.SocketError == SocketError.Success && e.LastOperation == SocketAsyncOperation.Receive)
{
string result = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred);
//Log(result);
GetDeviceDescriptionAsync(DD_Handler, result);
try
{
socket.ReceiveAsync(e);
}
catch (ObjectDisposedException)
{
Log("Socket is already disposed.");
}
}
});
rcv_event_args.Completed += RCV_Handler;
socket.SendToAsync(snd_event_args);
#elif WINDOWS_PHONE_APP||WINDOWS_APP||NETFX_CORE
var handler = new TypedEventHandler<DatagramSocket, DatagramSocketMessageReceivedEventArgs>(async (sender, args) =>
{
Log("Datagram message received");
if (timeout_called || args == null)
{
return;
}
string data;
using (var reader = args.GetDataReader())
{
data = reader.ReadString(reader.UnconsumedBufferLength);
}
Log(data);
await GetDeviceDescriptionAsync(data, args.LocalAddress).ConfigureAwait(false);
});
var adapters = await GetActiveAdaptersAsync().ConfigureAwait(false);
await Task.WhenAll(adapters.Select(async adapter =>
{
using (var socket = new DatagramSocket())
{
socket.Control.DontFragment = true;
socket.MessageReceived += handler;
try
{
await socket.BindServiceNameAsync("", adapter);
socket.JoinMulticastGroup(MULTICAST_HOST);
using (var output = await socket.GetOutputStreamAsync(MULTICAST_HOST, SSDP_PORT.ToString()))
{
using (var writer = new DataWriter(output))
{
writer.WriteBytes(data_byte);
await writer.StoreAsync();
}
}
await Task.Delay((timeout == null) ? DEFAULT_TIMEOUT : timeout.Value).ConfigureAwait(false);
Log("Search Timeout");
timeout_called = true;
}
catch (Exception e)
{
Log("Failed to send multicast: " + e.StackTrace);
}
finally
{
socket.MessageReceived -= handler;
}
}
})).ConfigureAwait(false);
#endif
#if WINDOWS_PHONE||DOT_NET
await Task.Delay((timeout == null) ? DEFAULT_TIMEOUT : timeout.Value).ConfigureAwait(false);
Log("Search Timeout");
timeout_called = true;
snd_event_args.Completed -= SND_Handler;
rcv_event_args.Completed -= RCV_Handler;
socket.Close();
#endif
OnTimeout(new EventArgs());
}
示例10: SearchDevices
//.........这里部分代码省略.........
}
catch (Exception)
{
//Invalid XML.
}
}
}
catch (WebException)
{
//Invalid DD location or network error.
}
});
#if WINDOWS_PHONE
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SendBufferSize = data_byte.Length;
SocketAsyncEventArgs snd_event_args = new SocketAsyncEventArgs();
snd_event_args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(multicast_address), ssdp_port);
snd_event_args.SetBuffer(data_byte, 0, data_byte.Length);
SocketAsyncEventArgs rcv_event_args = new SocketAsyncEventArgs();
rcv_event_args.SetBuffer(new byte[result_buffer], 0, result_buffer);
var SND_Handler = new EventHandler<SocketAsyncEventArgs>((sender, e) =>
{
if (e.SocketError == SocketError.Success && e.LastOperation == SocketAsyncOperation.SendTo)
{
socket.ReceiveBufferSize = result_buffer;
socket.ReceiveAsync(rcv_event_args);
}
});
snd_event_args.Completed += SND_Handler;
var RCV_Handler = new EventHandler<SocketAsyncEventArgs>((sender, e) =>
{
if (e.SocketError == SocketError.Success && e.LastOperation == SocketAsyncOperation.Receive)
{
string result = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred);
//Debug.WriteLine(result);
GetDDAsync(DD_Handler, result);
socket.ReceiveAsync(e);
}
});
rcv_event_args.Completed += RCV_Handler;
socket.SendToAsync(snd_event_args);
#elif NETFX_CORE
var sock = new DatagramSocket();
sock.MessageReceived += (sender, args) =>
{
if (timeout_called || args == null)
{
return;
}
var reader = args.GetDataReader();
string data = reader.ReadString(reader.UnconsumedBufferLength);
Debug.WriteLine(data);
GetDDAsync(DD_Handler, data);
};
try
{
await sock.BindServiceNameAsync(ssdp_port.ToString());
}
catch (Exception)
{
Debug.WriteLine("Duplicate search is not supported");
return;
}
var host = new HostName(multicast_address);
sock.JoinMulticastGroup(host);
try
{
var output = await sock.GetOutputStreamAsync(host, ssdp_port.ToString());
await output.WriteAsync(data_byte.AsBuffer());
await sock.OutputStream.FlushAsync();
}
catch (Exception)
{
Debug.WriteLine("Failed to send multicast");
return;
}
#endif
await RunTimeoutInvokerAsync(timeoutSec, () =>
{
Debug.WriteLine("SSDP Timeout");
timeout_called = true;
#if WINDOWS_PHONE
snd_event_args.Completed -= SND_Handler;
rcv_event_args.Completed -= RCV_Handler;
socket.Close();
#elif NETFX_CORE
sock.Dispose();
#endif
OnTimeout.Invoke();
});
}
示例11: Discover
protected override void Discover(Socket client, CancellationToken cancelationToken)
{
NextSearch = DateTime.UtcNow.AddSeconds(1);
var searchEndpoint = new IPEndPoint(
WellKnownConstants.IPv4MulticastAddress
/*IPAddress.Broadcast*/
, 1900);
foreach (var serviceType in ServiceTypes)
{
var datax = DiscoverDeviceMessage.Encode(serviceType);
var data = Encoding.ASCII.GetBytes(datax);
// UDP is unreliable, so send 3 requests at a time (per Upnp spec, sec 1.1.2)
// Yes, however it works perfectly well with just 1 request.
for (var i = 0; i < 2; i++)
{
if (cancelationToken.IsCancellationRequested) return;
var args = new SocketAsyncEventArgs {RemoteEndPoint = searchEndpoint};
args.SetBuffer(data, 0, data.Length);
client.SendToAsync(args);
}
}
}
示例12: StartSearch
public void StartSearch()
{
if (state == SearchState.Searching)
this.StopSearch(SearchStoppedReason.Aborted);
searchSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
var args = CreateSearchEventArgs();
searchSocket.SendToAsync(args);
retryTimer = new Timer(new TimerCallback(SearchRetry), null, TimeSpan.FromSeconds(searchRetrySeconds), TimeSpan.FromSeconds(searchRetrySeconds));
timeoutTimer = new Timer(new TimerCallback(SearchTimeout), null, TimeSpan.FromSeconds(searchTimeoutSeconds), TimeSpan.FromMilliseconds(-1));
state = SearchState.Searching;
}