• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Sockets.StreamSocket类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Windows.Networking.Sockets.StreamSocket的典型用法代码示例。如果您正苦于以下问题:C# StreamSocket类的具体用法?C# StreamSocket怎么用?C# StreamSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



StreamSocket类属于Windows.Networking.Sockets命名空间,在下文中一共展示了StreamSocket类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: ProcessRequestAsync

        private async void ProcessRequestAsync(StreamSocket socket)
        {
            try
            {
                // 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);
                }
            }
            catch (Exception ex)
            {
                await LogExceptionAsync(nameof(ProcessRequestAsync), ex);
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }
        }
开发者ID:torgeirhansen,项目名称:SimpleWeatherStation,代码行数:35,代码来源:HttpServer.cs


示例17: 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;
     }
 }
开发者ID:ballance,项目名称:MetroTorrent,代码行数:28,代码来源:ServerCommunicator.cs


示例18: WindowsNetSockets

 public WindowsNetSockets(string host, int port, bool ssl)
 {
     Socket = new StreamSocket();
     Host = host;
     Port = port;
     Ssl = ssl;
 }
开发者ID:achingono,项目名称:WinPhoneGmail,代码行数:7,代码来源:WindowsNetSockets.cs


示例19: ConnectAsync

        public async void ConnectAsync(string ipOrHost, int port, SocketEventArgs args)
        {
            _socket = new StreamSocket();
            var server = new HostName(ipOrHost);

            // TCP timeouts in WinRT are excessive, shorten them here using task cancellation
            var cts = new CancellationTokenSource();

            try
            {
                cts.CancelAfter(MqttProtocolInformation.Settings.NetworkTimeout * 1000);
                _logger.LogMessage("Socket", LogLevel.Verbose, string.Format("Authenticating client certificate with remote host CN={0}", server.CanonicalName));
                await _socket.ConnectAsync(server, port.ToString(), GetSocketProtectionLevel(args.EncryptionLevel)).AsTask(cts.Token);
                _clientUid = args.ClientUid;
                StartReceiving();
            }
            catch (TaskCanceledException)
            {
                args.SocketException = new IOException("Timeout error while trying to connect.");
                _clientUid = null;
                _socket.Dispose();
                _socket = null;
            }
            catch (Exception ex)
            {
                args.SocketException = ex;
                _clientUid = null;
                _socket.Dispose();
                _socket = null;
            }
            args.Complete();
        }
开发者ID:reicheltp,项目名称:KittyHawkMQ,代码行数:32,代码来源:Phone8SocketAdapter.cs


示例20: ReceiveImage

        private async void ReceiveImage(StreamSocket socket)
        {
            UpdateStatus("Empfange Daten...");

            // DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
            var reader = new DataReader(socket.InputStream);

            // Anzahl der Bytes abrufen, aus denen das Bild besteht
            // Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
            await reader.LoadAsync(4);
            int imageSize = reader.ReadInt32();

            // Bytearray des Bildes laden
            await reader.LoadAsync((uint)imageSize);
            byte[] imageBytes = new byte[imageSize];
            reader.ReadBytes(imageBytes);

            // Bytearray in Stream laden und anzeigen
            Dispatcher.BeginInvoke(() =>
            {
                using (var ms = new MemoryStream(imageBytes))
                {
                    var image = new BitmapImage();
                    image.SetSource(ms);

                    ReceivedImage.Source = image;
                }
            });
            UpdateStatus("Bild empfangen.");

            // Ressourcen freigeben
            reader.Dispose();
        }
开发者ID:GregOnNet,项目名称:WP8BookSamples,代码行数:33,代码来源:ClientPage.xaml.cs



注:本文中的Windows.Networking.Sockets.StreamSocket类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Sockets.StreamSocketListener类代码示例发布时间:2022-05-26
下一篇:
C# Sockets.DatagramSocket类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap