當前位置: 首頁>>代碼示例>>C#>>正文


C# Sockets.StreamSocket類代碼示例

本文整理匯總了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)
                {
                    
                }
            }
        }
開發者ID:peterdn,項目名稱:Geomoir,代碼行數:35,代碼來源:BluetoothClient.cs

示例2: HandleRequests

 private async Task HandleRequests(StreamSocket client)
 {
     using (client)
     {
         await HandleRequest(client);
     }
 }
開發者ID:rishabhbanga,項目名稱:CK.HomeAutomation,代碼行數:7,代碼來源:HttpServer.cs

示例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);
         }
     }
 }
開發者ID:SongOfSaya,項目名稱:MySocket,代碼行數:28,代碼來源:Scenario5_Certificates.xaml.cs

示例4: StateObject

 public StateObject(StreamSocket listener, int id = -1)
 {
     this.listener = listener;
     this.id = id;
     this.Close = false;
     this.Reset();
 }
開發者ID:Chrislaos,項目名稱:TheSocketThing,代碼行數:7,代碼來源:StateObject.cs

示例5: SocketHandler

        public SocketHandler(StreamSocket socket)
        {
            this.socket = socket;

            this.reader = new DataReader(this.socket.InputStream);
            this.writer = new DataWriter(this.socket.OutputStream);
        }
開發者ID:philipp2500,項目名稱:Remote-Content-Show,代碼行數:7,代碼來源:SocketHandler.cs

示例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);
            }
        }
開發者ID:Nick287,項目名稱:IoTDeviceService,代碼行數:29,代碼來源:HttpServer.cs

示例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;
     }
 }
開發者ID:svdvonde,項目名稱:bachelorproef,代碼行數:31,代碼來源:TCPSocketClient.cs

示例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;
     }
 }
開發者ID:peepo3663,項目名稱:WindowsPhone8,代碼行數:29,代碼來源:MainPage.xaml.cs

示例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);
        }
開發者ID:JimGaleForce,項目名稱:iot-build-lab,代碼行數:26,代碼來源:HttpServer.cs

示例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;
        }
開發者ID:cephalin,項目名稱:ContosoMoments,代碼行數:33,代碼來源:Utils.cs

示例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();
            }
        }
開發者ID:wleev,項目名稱:Catnap.Server,代碼行數:31,代碼來源:HttpServer.cs

示例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;
        }
開發者ID:wleev,項目名稱:Catnap.Server,代碼行數:28,代碼來源:HttpRequest.cs

示例13: ExternalAdmin

        public ExternalAdmin(StreamSocket socket)
        {
            this.socketHandler = new SocketHandler(socket);

            this.socketHandler.OnMessageBytesReceived += SocketHandler_OnMessageBytesReceived;
            this.socketHandler.Start();
        }
開發者ID:philipp2500,項目名稱:Remote-Content-Show,代碼行數:7,代碼來源:ExternalAdmin.cs

示例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);
            }
        }
開發者ID:GudoshnikovaAnna,項目名稱:qreal,代碼行數:33,代碼來源:SocketClient.cs

示例15: ParseRequestStream

 internal async Task<HttpRequest> ParseRequestStream(StreamSocket httpRequestSocket)
 {
     using (var inputStream = httpRequestSocket.InputStream)
     {
         return await ParseRequestStream(inputStream);
     }
 }
開發者ID:Ferho,項目名稱:restup,代碼行數:7,代碼來源:HttpRequestParser.cs


注:本文中的Windows.Networking.Sockets.StreamSocket類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。