本文整理汇总了C#中Windows.Networking.Sockets.StreamSocket类的典型用法代码示例。如果您正苦于以下问题:C# StreamSocket类的具体用法?C# StreamSocket怎么用?C# StreamSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
StreamSocket类属于Windows.Networking.Sockets命名空间,在下文中一共展示了StreamSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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)
{
}
}
}
示例2: HandleRequests
private async Task HandleRequests(StreamSocket client)
{
using (client)
{
await HandleRequest(client);
}
}
示例3: ConnectSocket_Click
private async void ConnectSocket_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(ServiceNameForConnect.Text))
{
rootPage.NotifyUser("请提供服务器名", NotifyType.ErrorMessage);
return;
}
HostName hostName;
try
{
hostName = new HostName(HostNameForConnect.Text);
}
catch (ArgumentException)
{
rootPage.NotifyUser("错误:无效主机名", NotifyType.ErrorMessage);
return;
}
rootPage.NotifyUser("连接至" + HostNameForConnect.Text, NotifyType.StatusMessage);
using (StreamSocket socket = new StreamSocket())
{
socket.Control.ClientCertificate = null;
bool shouldRetry = await TryConnectSocketWithRetryAsync(socket, hostName);
if (shouldRetry)
{
await TryConnectSocketWithRetryAsync(socket, hostName);
}
}
}
示例4: StateObject
public StateObject(StreamSocket listener, int id = -1)
{
this.listener = listener;
this.id = id;
this.Close = false;
this.Reset();
}
示例5: SocketHandler
public SocketHandler(StreamSocket socket)
{
this.socket = socket;
this.reader = new DataReader(this.socket.InputStream);
this.writer = new DataWriter(this.socket.OutputStream);
}
示例6: ProcessRequestAsync
private async void ProcessRequestAsync(StreamSocket socket)
{
// Read in the HTTP request, we only care about type 'GET'
StringBuilder request = new StringBuilder();
using (IInputStream input = socket.InputStream)
{
byte[] data = new byte[bufLen];
IBuffer buffer = data.AsBuffer();
uint dataRead = bufLen;
while (dataRead == bufLen)
{
await input.ReadAsync(buffer, bufLen, InputStreamOptions.Partial);
request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
dataRead = buffer.Length;
}
if (RecivedMeg != null)
{
Debug.WriteLine(request.ToString());
RecivedMeg(request.ToString(), EventArgs.Empty);
}
}
using (IOutputStream output = socket.OutputStream)
{
string requestMethod = request.ToString().Split('\n')[0];
string[] requestParts = requestMethod.Split(' ');
await WriteResponseAsync(requestParts, output);
}
}
示例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: PeerFinder_TriggeredConnectionStateChanged
void PeerFinder_TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs args)
{
switch (args.State)
{
case TriggeredConnectState.Listening:
Deployment.Current.Dispatcher.BeginInvoke(() =>
state.Text = "Listening");
// 作为主机正在监听等待连接
break;
case TriggeredConnectState.PeerFound:
Deployment.Current.Dispatcher.BeginInvoke(() =>
state.Text = "PeerFound");
// 触碰完成
break;
case TriggeredConnectState.Connecting:
// 正在连接
break;
case TriggeredConnectState.Completed:
// 连接完成返回 StreamSocket对象可用于进行收发消息
_streamSocket = args.Socket;
break;
case TriggeredConnectState.Canceled:
//在完成之前,连接已停止
break;
case TriggeredConnectState.Failed:
// 连接失败
break;
}
}
示例9: ProcessRequestAsync
private async void ProcessRequestAsync(StreamSocket socket)
{
weatherShield.GreenLEDPin.Write(GpioPinValue.High);
// Read in the HTTP request, we only care about type 'GET'
StringBuilder request = new StringBuilder();
using (IInputStream input = socket.InputStream)
{
byte[] data = new byte[bufLen];
IBuffer buffer = data.AsBuffer();
uint dataRead = bufLen;
while (dataRead == bufLen)
{
await input.ReadAsync(buffer, bufLen, InputStreamOptions.Partial);
request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
dataRead = buffer.Length;
}
}
using (IOutputStream output = socket.OutputStream)
{
string requestMethod = request.ToString().Split('\n')[0];
string[] requestParts = requestMethod.Split(' ');
await WriteResponseAsync(requestParts, output);
}
weatherShield.GreenLEDPin.Write(GpioPinValue.Low);
}
示例10: 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;
}
示例11: ProcessRequestAsync
private async void ProcessRequestAsync(StreamSocket socket)
{
HttpRequest request;
try
{
request = HttpRequest.Read(socket);
}
catch (Exception ex)
{
await WriteInternalServerErrorResponse(socket, ex);
return;
}
if (AcceptedVerbs.Contains(request.Method.Method))
{
HttpResponse response;
try
{
response = await restHandler.Handle(request);
}
catch (Exception ex)
{
await WriteInternalServerErrorResponse(socket, ex);
return;
}
await WriteResponse(response, socket);
await socket.CancelIOAsync();
socket.Dispose();
}
}
示例12: Read
public static HttpRequest Read(StreamSocket socket)
{
HttpRequest request = new HttpRequest();
using (var input = socket.InputStream)
{
using (var reader = new StreamReader(input.AsStreamForRead()))
{
var requestHeader = reader.ReadLine();
var headerSegments = requestHeader.Split(' ');
request.Method = new HttpMethod(headerSegments[0]);
request.Path = new Uri(headerSegments[1], UriKind.RelativeOrAbsolute);
request.Version = GetHttpVersion(headerSegments[2]);
if (request.Version.Equals(HttpVersion.Http10))
request.Headers.Add("Host", $"{socket.Information.LocalAddress}:{socket.Information.LocalPort}");
ParseRequest(reader, request);
if (!request.Path.IsAbsoluteUri)
request.Path = new UriBuilder("http", socket.Information.LocalAddress.ToString(), int.Parse(socket.Information.LocalPort), request.Path.OriginalString).Uri;
}
}
return request;
}
示例13: ExternalAdmin
public ExternalAdmin(StreamSocket socket)
{
this.socketHandler = new SocketHandler(socket);
this.socketHandler.OnMessageBytesReceived += SocketHandler_OnMessageBytesReceived;
this.socketHandler.Start();
}
示例14: Connect
public static void Connect(string address, string port)
{
if (!connected)
{
clientSocket = new StreamSocket();
try
{
serverHost = new HostName(address);
serverPort = port;
serverHostnameString = address;
writer = new DataWriter(clientSocket.OutputStream);
clientSocket.ConnectAsync(serverHost, serverPort);
connected = true;
}
catch (Exception)
{
clientSocket.Dispose();
clientSocket = null;
throw new ConnectionErrorException();
}
}
else
{
clientSocket.Dispose();
clientSocket = null;
connected = false;
GamepadClient.Connect(address, port);
}
}
示例15: ParseRequestStream
internal async Task<HttpRequest> ParseRequestStream(StreamSocket httpRequestSocket)
{
using (var inputStream = httpRequestSocket.InputStream)
{
return await ParseRequestStream(inputStream);
}
}