本文整理汇总了C#中Windows.Networking.Sockets.StreamSocket.ConnectAsync方法的典型用法代码示例。如果您正苦于以下问题:C# StreamSocket.ConnectAsync方法的具体用法?C# StreamSocket.ConnectAsync怎么用?C# StreamSocket.ConnectAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Networking.Sockets.StreamSocket
的用法示例。
在下文中一共展示了StreamSocket.ConnectAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendMessage
public async void SendMessage(string msg)
{
HostName hostName;
try
{
hostName = new HostName("localhost");
}
catch (ArgumentException)
{
return;
}
StreamSocket socket;
try
{
using (socket = new StreamSocket())
{
await socket.ConnectAsync(hostName, port2);
//CoreApplication.Properties.Add("connected", null);
DataWriter dw = new DataWriter(socket.OutputStream);
dw.WriteString(msg);
await dw.StoreAsync();
}
}
catch
{
//break;
}
}
示例2: ConnectTo
public async void ConnectTo(Slide slide)
{
var duration = slide.AppearanceDuration;
var content = slide.Content as ScreenCapture;
var ipAddress = content.IPTargetAgent;
HostName localHost = null;
foreach (var hostName in NetworkInformation.GetHostNames())
{
if(hostName.IPInformation != null)
{
if(hostName.Type == Windows.Networking.HostNameType.Ipv4)
{
localHost = hostName;
}
}
}
var TCPClient = new StreamSocket();
try
{
var cts = new CancellationTokenSource();
cts.CancelAfter(500);
var connectAsync = TCPClient.ConnectAsync(
new Windows.Networking.EndpointPair(localHost, "54321", new Windows.Networking.HostName(ipAddress), "54321"));
var connectTask = connectAsync.AsTask(cts.Token);
await connectTask;
this.SendToAgent(slide, TCPClient);
}
catch(Exception ex)
{
TCPClient.Dispose();
Debug.WriteLine(ex.Message);
this.FireOnConnectionFailed();
return;
}
}
示例3: ConnectToSignalingServer
public ConnectionStatus ConnectToSignalingServer(ConnectionOwner connectionOwner)
{
try
{
SignaledPeerData.Reset();
SignalingStatus.Reset();
SignaledRelayMessages.Reset();
var socket = new StreamSocket();
socket.EnableTransferOwnership(Guid.Parse(connectionOwner.OwnerId),
SocketActivityConnectedStandbyAction.Wake);
socket.ConnectAsync(new HostName(SignalingSettings.SignalingServerHost),
SignalingSettings.SignalingServerPort, SocketProtectionLevel.PlainSocket)
.AsTask()
.Wait();
socket.TransferOwnership(SignalingSocketOperation.SignalingSocketId);
return new ConnectionStatus
{
IsConnected = true
};
}
catch (Exception exception)
{
return new ConnectionStatus
{
IsConnected = false
};
}
}
示例4: TryConnect
private async void TryConnect ( )
{
if ( connectList.SelectedItem != null )
{
try
{
PeerFinder.Start( );
PeerFinder.AlternateIdentities[ "Bluetooth:Paired" ] = "";
var pairedDevices = await PeerFinder.FindAllPeersAsync();
UpdateStatus( "Connecting to selected device: " + pairedDevices[ connectList.SelectedIndex ].DisplayName );
socket = new StreamSocket(); // Create socket.
await socket.ConnectAsync( pairedDevices[ connectList.SelectedIndex ].HostName, "1" ); // Connect to device using socket.
connected = true;
textblockDevice.Text = "Connected to " + pairedDevices[ connectList.SelectedIndex ].DisplayName;
UpdateStatus( "success!" );
WaitForData( socket );
Write( "#p" ); // First ping to test connection.
}
catch ( Exception ex )
{
UpdateStatus( "Error: " + ex.Message + "," + ex.StackTrace );
}
}
else
{
UpdateStatus( "Please select a device." );
}
}
示例5: Connect
public async Task Connect()
{
PeerFinder.AlternateIdentities["Bluetooth:SDP"] = ServiceGUID.ToString();
var peers = await PeerFinder.FindAllPeersAsync();
foreach (var p in peers)
{
var h = p.ServiceName;
}
// TODO: obviously list these instead of taking the first
var peer = peers.FirstOrDefault();
if (peer != null)
{
var socket = new StreamSocket();
try
{
// default service name?
await socket.ConnectAsync(peer.HostName, ServiceName);
var connection = new DuplexConnection(socket);
var device = new BluetoothDevice(peer.DisplayName, peer.HostName, peer.ServiceName);
if (ConnectionEstablished != null)
{
ConnectionEstablished(this, new ClientConnectedEventArgs(device, connection));
}
}
catch (Exception ex)
{
}
}
}
示例6: CheckServerAddressWP
public static async Task<bool> CheckServerAddressWP(string url, int port = 80, int msTimeout = 5000)
{
bool retVal = false;
string originalUrl = url;
if (!IsUrlValid(url))
return retVal;
try
{
using (var tcpClient = new StreamSocket())
{
url = url.Replace("http://", string.Empty).Replace("https://", string.Empty);
if (url.Last() == '/')
url = url.Substring(0, url.Length - 1);
await tcpClient.ConnectAsync(new Windows.Networking.HostName(url), port.ToString(), SocketProtectionLevel.PlainSocket);
if (tcpClient.Information.RemoteHostName.ToString().ToLower() == url.ToLower())
retVal = true;
tcpClient.Dispose();
}
}
catch (Exception ex)
{
retVal = false;
}
retVal &= await ExposesContosoMomentsWebAPIs(originalUrl);
return retVal;
}
示例7: Connect
/// <summary>
/// Attempt to create a tcp connection to a certain host
/// </summary>
/// <param name="remoteAddress">Address of the remote host</param>
/// <param name="connectionTimeout">Time (in milliseconds) that defines how long we should attempt to connect to the other party</param>
/// <returns>Returns a StreamSocket to the remote host</returns>
private async Task<StreamSocket> Connect(string remoteAddress, int connectionTimeout)
{
StreamSocket streamSocket = new StreamSocket();
// Make sure a timeout occurs (otherwise it will try to connect forever)
CancellationTokenSource cts = new CancellationTokenSource();
try
{
cts.CancelAfter(connectionTimeout);
// Try to connect to the remote address
await streamSocket.ConnectAsync(new HostName(remoteAddress), this.port).AsTask(cts.Token);
return streamSocket;
}
catch (TaskCanceledException ex)
{
// TaskCanceledException will be thrown when the timeout has passed.
// Now throw our own exception
throw new ConnectionTimedOutException("Could not create connection with host " + remoteAddress + " within the given time-out period of " + connectionTimeout + "ms. ");
}
catch (System.Exception ex)
{
// Catch any other exception too
System.Diagnostics.Debug.WriteLine("Exception occured in TCPSocketClient.Connect: " + ex);
throw;
}
}
示例8: ConnectAsync
public static async Task<bool> ConnectAsync()
{
if (imageComparisonServer != null)
return true;
try
{
imageComparisonServer = new StreamSocket();
await imageComparisonServer.ConnectAsync(new HostName(ParadoxImageServerHost), ParadoxImageServerPort.ToString());
// Send initial parameters
using (var memoryStream = new MemoryStream())
{
var binaryWriter = new BinaryWriter(memoryStream);
ImageTestResultConnection.Write(binaryWriter);
var dataWriter = new DataWriter(imageComparisonServer.OutputStream);
dataWriter.WriteBytes(memoryStream.ToArray());
await dataWriter.StoreAsync();
await dataWriter.FlushAsync();
dataWriter.DetachStream();
}
return true;
}
catch (Exception)
{
imageComparisonServer = null;
return false;
}
}
示例9: RefreshLogsTapped
private async void RefreshLogsTapped(object sender, TappedRoutedEventArgs e)
{
var btn = sender as Button;
if (btn != null)
{
btn.IsEnabled = false;
try
{
using (var socket = new StreamSocket())
{
await socket.ConnectAsync(new HostName(@"127.0.0.1"), @"11111");
var handler = new WinRtTransferHandler(socket);
_viewModel.Load(await new LogsClientHandler(2, handler).GetConfigsAsync());
await handler.CloseAsync();
}
}
catch
{
}
finally
{
btn.IsEnabled = true;
}
}
}
示例10: DoCommand
private async Task<string> DoCommand(string command)
{
StringBuilder strBuilder = new StringBuilder();
using (StreamSocket clientSocket = new StreamSocket())
{
await clientSocket.ConnectAsync(new HostName("192.168.9.108"), "9001");
using (DataWriter writer = new DataWriter(clientSocket.OutputStream))
{
writer.WriteString(command);
await writer.StoreAsync();
writer.DetachStream();
}
using (DataReader reader = new DataReader(clientSocket.InputStream))
{
reader.InputStreamOptions = InputStreamOptions.Partial;
await reader.LoadAsync(8192);
while (reader.UnconsumedBufferLength > 0)
{
strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
await reader.LoadAsync(8192);
}
reader.DetachStream();
}
}
return (strBuilder.ToString());
}
示例11: TcpTextWriter
public TcpTextWriter(string hostName, int port)
{
if (hostName == null)
throw new ArgumentNullException(nameof(hostName));
if ((port < 0) || (port > ushort.MaxValue))
throw new ArgumentException("port");
HostName = hostName;
Port = port;
#if __IOS__ || MAC
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
#endif
try
{
#if __IOS__ || MAC || ANDROID
var client = new TcpClient(hostName, port);
writer = new StreamWriter(client.GetStream());
#elif WINDOWS_PHONE || NETFX_CORE
var socket = new StreamSocket();
socket.ConnectAsync(new HostName(hostName), port.ToString(CultureInfo.InvariantCulture))
.AsTask()
.ContinueWith( _ => writer = new StreamWriter(socket.OutputStream.AsStreamForWrite()));
#endif
}
catch
{
#if __IOS__ || MAC
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
#endif
throw;
}
}
示例12: ConnectAsync
internal async Task ConnectAsync(
HostName hostName,
string serviceName,
string user,
string password)
{
if (controlStreamSocket != null)
{
throw new InvalidOperationException("Control connection already started.");
}
this.hostName = hostName;
controlStreamSocket = new StreamSocket();
await controlStreamSocket.ConnectAsync(hostName, serviceName);
reader = new DataReader(controlStreamSocket.InputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;
writer = new DataWriter(controlStreamSocket.OutputStream);
readCommands = new List<string>();
loadCompleteEvent = new AutoResetEvent(false);
readTask = InfiniteReadAsync();
FtpResponse response;
response = await GetResponseAsync();
VerifyResponse(response, 220);
response = await UserAsync(user);
VerifyResponse(response, 331);
response = await PassAsync(password);
VerifyResponse(response, 230);
}
示例13: ConnectAsync
public async Task<bool> ConnectAsync(string host, int port, int timeOut = 5000)
{
try
{
socket = new StreamSocket();
socket.Control.KeepAlive = true;
var cts = new CancellationTokenSource();
cts.CancelAfter(timeOut);
await socket.ConnectAsync(new HostName(host), port.ToString()).AsTask(cts.Token);
ReceiveAsync();
return true;
}
catch (TaskCanceledException)
{
}
catch (Exception ex)
{
//if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
// throw;
}
Disconnect();
return false;
}
示例14: IsReachable
/// <summary>
/// Checks if remote is reachable. RT apps cannot do loopback so this will alway return false.
/// You can use it to check remote calls though.
/// </summary>
/// <param name="host"></param>
/// <param name="msTimeout"></param>
/// <returns></returns>
public override async Task<bool> IsReachable(string host, int msTimeout = 5000)
{
if (string.IsNullOrEmpty(host))
throw new ArgumentNullException("host");
if (!IsConnected)
return false;
try
{
var serverHost = new HostName(host);
using(var client = new StreamSocket())
{
await client.ConnectAsync(serverHost, "http");
return true;
}
}
catch(Exception ex)
{
Debug.WriteLine("Unable to reach: " + host + " Error: " + ex);
return false;
}
}
示例15: ConnectAsyncInternal
private async Task ConnectAsyncInternal(HostName hostName)
{
_tokenSource = new CancellationTokenSource();
_socket = new StreamSocket();
// połącz z kontrolerem na porcie 5555
await _socket.ConnectAsync(hostName, "5555", SocketProtectionLevel.PlainSocket);
// wyslij komendę odblokowującą
await _socket.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(UnlockCommand).AsBuffer());
// read the "Accept:EV340\r\n\r\n" response
//stworzenie bufor na odpowiedź
IBuffer bufferResponse = new Buffer(128);
//pobranie do bufora odpowiedzi przychodzącej od kontrolera EV3
await _socket.InputStream.ReadAsync(bufferResponse, bufferResponse.Capacity, InputStreamOptions.Partial);
//przekształcenie danych z bufora na ciag znaków w formacie UTF8
string response = Encoding.UTF8.GetString(bufferResponse.ToArray(), 0, (int)bufferResponse.Length);
if (string.IsNullOrEmpty(response))
//zgłoszenie błędu w razie braku odpowiedzi
throw new Exception("LEGO EV3 brick did not respond to the unlock command.");
//rozpoczęcie pobierania danych
await ThreadPool.RunAsync(PollInput);
}