本文整理汇总了C#中Windows.Networking.Sockets.DatagramSocket.ConnectAsync方法的典型用法代码示例。如果您正苦于以下问题:C# DatagramSocket.ConnectAsync方法的具体用法?C# DatagramSocket.ConnectAsync怎么用?C# DatagramSocket.ConnectAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Networking.Sockets.DatagramSocket
的用法示例。
在下文中一共展示了DatagramSocket.ConnectAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetNetworkTimeAsync
/// <summary>
/// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
/// </summary>
/// <param name="timeout">Operation timeout.</param>
/// <returns>Network accurate <see cref="DateTime"/> value.</returns>
public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout)
{
using (var socket = new DatagramSocket())
using (var ct = new CancellationTokenSource(timeout))
{
ct.Token.Register(() => _resultCompletionSource.TrySetCanceled());
socket.MessageReceived += OnSocketMessageReceived;
//The UDP port number assigned to NTP is 123
await socket.ConnectAsync(new HostName("pool.ntp.org"), "123");
using (var writer = new DataWriter(socket.OutputStream))
{
// NTP message size is 16 bytes of the digest (RFC 2030)
var ntpBuffer = new byte[48];
// Setting the Leap Indicator,
// Version Number and Mode values
// LI = 0 (no warning)
// VN = 3 (IPv4 only)
// Mode = 3 (Client Mode)
ntpBuffer[0] = 0x1B;
writer.WriteBytes(ntpBuffer);
await writer.StoreAsync();
var result = await _resultCompletionSource.Task;
return result;
}
}
}
示例2: Start
public override async void Start()
{
if (_Started)
return;
_SequenceNumber = 1;
try
{
// Connect to the Drone
udpClient = new DatagramSocket();
await udpClient.BindServiceNameAsync(_ServiceName);
await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
udpWriter = new DataWriter(udpClient.OutputStream);
udpWriter.WriteByte(1);
await udpWriter.StoreAsync();
_Timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25));
_Started = true;
}
catch (Exception)
{
Stop();
}
}
示例3: Start
public void Start()
{
_socket = new DatagramSocket();
_socket.Control.DontFragment = true;
_socket.ConnectAsync(new HostName("255.255.255.255"), "19227").AsTask().Wait();
_outputStream = _socket.OutputStream.AsStreamForWrite();
_timer.Change(0, Timeout.Infinite);
}
示例4: SendResponseAsync
private async Task SendResponseAsync(HostName target, DiscoveryResponse response)
{
var buffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response));
using (var socket = new DatagramSocket())
{
await socket.ConnectAsync(target, DEFAULT_PORT.ToString());
await socket.OutputStream.WriteAsync(buffer.AsBuffer());
await socket.OutputStream.FlushAsync();
}
}
示例5: ConnectedToServer
public async void ConnectedToServer()
{
// 资料来自 http://www.devdiv.com/forum.php?mod=viewthread&tid=134558
//创建一个本地连接
udpSocket = new DatagramSocket();
//创建新的hostName
HostName remoteHost = new HostName("168.63.151.29");
//打开一个至远程主机的连接,后面是远程端口号。。
await udpSocket.ConnectAsync(remoteHost, "3000");
}
示例6: StartupAsync
public async Task<bool> StartupAsync(string serverIP, int serverPort)
{
await ShutdownAsync();
IsRunning = true;
messageReceiptAwaiters = new Stack<TaskCompletionSource<byte[]>>();
socket = new DatagramSocket();
socket.MessageReceived += socket_MessageReceived;
await socket.ConnectAsync(new HostName(serverIP), serverPort.ToString());
return true;
}
示例7: Start
public override async void Start()
{
udpClient = new DatagramSocket();
// Connect To Drone
udpClient.MessageReceived += MessageReceived;
await udpClient.BindServiceNameAsync(_ServiceName);
await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
udpWriter = new DataWriter(udpClient.OutputStream);
SendKeepAliveSignal();
_TimeoutStopWatch = Stopwatch.StartNew();
}
示例8: OnNavigatedTo
/// <summary>
/// 在此页将要在 Frame 中显示时进行调用。
/// </summary>
/// <param name="e">描述如何访问此页的事件数据。Parameter
/// 属性通常用于配置页。</param>
async protected override void OnNavigatedTo(NavigationEventArgs e)
{
// 创建一个新的socket实例,并绑定到一个本地端口上
DatagramSocket udpSocket = new DatagramSocket();
await udpSocket.BindServiceNameAsync("3721");
// 打开一个连接到远程主机上
HostName remoteHost = new HostName("192.168.1.100");
await udpSocket.ConnectAsync(remoteHost, "3721");
// 将一个字符串以UDP数据包形式发送到远程主机上
DataWriter udpWriter = new DataWriter(udpSocket.OutputStream);
udpWriter.WriteString("这里是破船之家");
await udpWriter.StoreAsync();
}
示例9: SynchronizeDeviceTime
public static async void SynchronizeDeviceTime()
{
DatagramSocket socket = new DatagramSocket();
socket.MessageReceived += DatagramSocket_MessageReceived;
await socket.ConnectAsync(new HostName("time.windows.com"), "123");
using (DataWriter writer = new DataWriter(socket.OutputStream))
{
byte[] container = new byte[48];
container[0] = 0x1B;
writer.WriteBytes(container);
await writer.StoreAsync();
}
}
示例10: connect
/// <summary>
/// connect to server
/// </summary>
/// <param name="_host">target ip address</param>
/// <param name="_axisPort">axis channel port</param>
/// <param name="_ctlPort">control channel port</param>
/// <param name="_trackPort">track channel port</param>
/// <returns></returns>
public async Task connect(string _host,int _axisPort,int _ctlPort, int _trackPort)
{
host = _host; trackPort = _trackPort;
AxisBuffer = new byte[AxisMsgSize];
CtlBuffer = new byte[CtlMsgSize];
trackBuffer = new byte[trackMsgSize];
//connecting
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
axisSocket = new DatagramSocket();
ctlSocket = new DatagramSocket();
trackSocket = new DatagramSocket();
HostName hostname = new HostName(host);
await axisSocket.ConnectAsync(hostname, _axisPort.ToString());
await ctlSocket.ConnectAsync(hostname, _ctlPort.ToString());
await trackSocket.ConnectAsync(hostname, trackPort.ToString());
connected = true;
}
示例11: SendTimeRequest
async partial void SendTimeRequest()
{
var socket = new Windows.Networking.Sockets.DatagramSocket();
AsyncUdpResult asyncResult = null;
try
{
var buffer = new byte[48];
buffer[0] = 0x1B;
socket.MessageReceived += Socket_Completed_Receive;
asyncResult = new AsyncUdpResult(socket);
await socket.ConnectAsync(new Windows.Networking.HostName(_ServerAddress), "123").AsTask().ConfigureAwait(false);
using (var udpWriter = new DataWriter(socket.OutputStream))
{
udpWriter.WriteBytes(buffer);
await udpWriter.StoreAsync().AsTask().ConfigureAwait(false);
udpWriter.WriteBytes(buffer);
await udpWriter.StoreAsync().AsTask().ConfigureAwait(false);
asyncResult.Wait(OneSecond);
}
}
catch (Exception ex)
{
try
{
if (socket != null)
{
ExecuteWithSuppressedExceptions(() => socket.MessageReceived -= this.Socket_Completed_Receive);
ExecuteWithSuppressedExceptions(() => socket.Dispose());
}
}
finally
{
OnErrorOccurred(ExceptionToNtpNetworkException(ex));
}
}
finally
{
asyncResult?.Dispose();
}
}
示例12: WakeAsync
public static async Task WakeAsync(HostName endPoint, int port, byte[] macAddress)
{
var packet = new List<byte>();
for (var i = 0; i < 6; i++) // Trailer of 6 FF packets
packet.Add(0xFF);
for (var i = 0; i < 16; i++) // Repeat 16 times the MAC address
packet.AddRange(macAddress);
using (var socket = new DatagramSocket())
{
await socket.ConnectAsync(endPoint, port.ToString());
var stream = socket.OutputStream;
using (var writer = new DataWriter(stream))
{
writer.WriteBytes(packet.ToArray());
await writer.StoreAsync();
}
}
}
示例13: Locate
public async void Locate()
{
DatagramSocket socket = new DatagramSocket();
//socket.Control.DontFragment = true;
socket.MessageReceived += MessageReceived;
try
{
//// Connect to the server (in our case the listener we created in previous step).
await socket.ConnectAsync(new HostName("255.255.255.255"), "8888");
//await socket.ConnectAsync(new HostName("192.168.1.177"), "8888");
//rootPage.NotifyUser("Connected", NotifyType.StatusMessage);
// Mark the socket as connected. Set the value to null, as we care only about the fact that the property is set.
//CoreApplication.Properties.Add("connected", null);
DataWriter udpWriter = new DataWriter(socket.OutputStream);
udpWriter.WriteString("SNC");
await udpWriter.StoreAsync();
//byte[] msg = new byte[] { 35, 36, 37 };
//IOutputStream stream = await socket.GetOutputStreamAsync(new HostName("255.255.255.255"), "8888");
//await stream.WriteAsync(BytesToBuffer(msg));
}
catch (Exception exception)
{
// If this is an unknown status it means that the error is fatal and retry will likely fail.
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
//rootPage.NotifyUser("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage);
}
}
示例14: Start
public override async void Start()
{
if (_Started)
return;
_SequenceNumber = 1;
// Connect To Drone
udpClient = new DatagramSocket();
await udpClient.BindServiceNameAsync(_ServiceName);
await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
udpWriter = new DataWriter(udpClient.OutputStream);
//string path = string.Format("AR.Drone-CommandHistory_{0:yyyy-MM-dd-HH-mm}.txt", DateTime.Now);
//commandHistoryFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting);
// Write first message
//byte[] firstMessage = BitConverter.GetBytes(1);
//WriteString(firstMessage.ToString());
udpWriter.WriteByte(1);
await udpWriter.StoreAsync();
_Timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25));
_Started = true;
}
示例15: connectButton_Click
/// <summary>
/// 连接Udp服务
/// </summary>
private async void connectButton_Click(object sender, RoutedEventArgs e)
{
hostName = new HostName(hostIP.Text);
DatagramSocket socket = new DatagramSocket();
CoreApplication.Properties.Add("clientSocket", socket);
try
{
await socket.ConnectAsync(hostName, hostPort.Text);
CoreApplication.Properties.Add("connected", null);
}
catch (Exception ee)
{
}
finally
{
connectButton.IsEnabled = false;
_accelerometer = Accelerometer.GetDefault();
if (_accelerometer != null)
{
// Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
// This value will be used later to activate the sensor.
// send();
//}
uint minReportInterval = _accelerometer.MinimumReportInterval;
_desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
_accelerometer.ReportInterval = _desiredReportInterval;
_accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);
readyToSend();
}
else
{
readyToSend();
MessageDialog msg = new MessageDialog("No accelerometer found");
msg.ShowAsync();
}
}
}