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

C# Sockets.StreamSocketListener类代码示例

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

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



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

示例1: OnConnectionReceived

 private void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     if ((m_handler != null) && m_running)
     {
         IAsyncAction asyncAction = ThreadPool.RunAsync((workItem) =>
             {
                 StreamSocket s = args.Socket;
                 try
                 {
                     m_handler(
                         this,
                         s.Information.RemoteHostName.CanonicalName.ToString(),
                         s.InputStream.AsStreamForRead(),
                         s.OutputStream.AsStreamForWrite()
                         );
                 }
                 catch (Exception)
                 {
                     // Quietly consume the exception
                 }
                 // Close the client socket
                 s.Dispose();
             });
     }
 }
开发者ID:ossandust,项目名称:iotweb,代码行数:25,代码来源:SocketServer.cs


示例2: listener_ConnectionReceived

        private void listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            this.Log("new Connection received");
            _output = args.Socket.OutputStream;
            try
            {
                using (var reader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
                {
                    while (!reader.EndOfStream)
                    {
                        var nextLine = reader.ReadLine();
                        this.Log(nextLine);
                        _input.OnNext(nextLine);
                    }
                }
                _input.OnCompleted();

            }
            catch (Exception ex)
            {
                this.Log("exception, invalidating socket stuff");
                InvalidateSocketStuff();
                _input.OnError(ex);
            }
        }
开发者ID:journeyman,项目名称:httpServerProxy,代码行数:25,代码来源:ServerProxy.cs


示例3: Listener_ConnectionReceived

 private void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     if (this.OnConnectionReceived != null)
     {
         this.OnConnectionReceived(args.Socket);
     }
 }
开发者ID:philipp2500,项目名称:Remote-Content-Show,代码行数:7,代码来源:Server.cs


示例4: OnConnectionReceived

        private async void OnConnectionReceived(
            StreamSocketListener sender,
            StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                DisplayOutput(TcpServerOutput, args.Socket.Information.RemoteAddress.DisplayName + " connected.");

                while (true)
                {
                    // Read request.
                    string request = await ReadUntilCrLf(args.Socket.InputStream, TcpServerOutput);
                    if (String.IsNullOrEmpty(request))
                    {
                        // If there was no request. The remote host closed the connection.
                        return;
                    }
                    DisplayOutput(TcpServerOutput, request);

                    // Send response.
                    string response = "Yes, I am ñoño. The time is " + DateTime.Now + ".\r\n";

                    // In this sample since the server doesn´t close the close the socket, we
                    // could do it async (i.e. without await)., but not now.
                    await Send(args.Socket.OutputStream, response);
                }
            }
            catch (Exception ex)
            {
                DisplayOutput(TcpServerOutput, ex.ToString());
            }
        }
开发者ID:kiewic,项目名称:Projects,代码行数:32,代码来源:MainPage.xaml.cs


示例5: TcpServer_ConnectionReceived

 private async void TcpServer_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     if (isRunning)
     {
         await ThreadPool.RunAsync(new WorkItemHandler((IAsyncResult) => AddClient(args)));
     }
 }
开发者ID:notdef1ned,项目名称:voice-chat-winrt,代码行数:7,代码来源:ChatServer.cs


示例6: OnConnectionReceived

        private async void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            playPage.DisplayMessages(name + " :Recived TCP: start");
            try
            {
                playPage.DisplayMessages(name + " " + args.Socket.Information.RemoteAddress.DisplayName + " connected.");
                while (true)
                {
                    string request = await Read(args.Socket.InputStream);

                    if (String.IsNullOrEmpty(request))
                    {
                        return;
                    }
                    playPage.DisplayMessages(name + " :Recived TCP: " + request);
                    OnReceived(request, args.Socket.Information.RemoteAddress.DisplayName, args.Socket.Information.RemotePort);
                    //string response = "Respone.\r\n";
                    //await Send(args.Socket.OutputStream, response);
                }
            }
            catch (Exception ex)
            {
                playPage.DisplayMessages(name + " :Recived TCP\n" + ex.ToString());
            }
        }
开发者ID:Pooler22,项目名称:OfficeTheGame,代码行数:25,代码来源:TCPClientRemote.cs


示例7: TinyHttpdServer

 // private AppServiceConnection appServiceConnection;
 public TinyHttpdServer(int serverPort)
 {
     listener = new StreamSocketListener();
     port = serverPort;
     listener.ConnectionReceived += (s, e) =>
                     ProcessRequestAsync(e.Socket);
 }
开发者ID:donma,项目名称:Windows10IoT-TinyHttpServer,代码行数:8,代码来源:TinyHttpdServer.cs


示例8: HttpServer

        public HttpServer(int serverPort, Func<string, string> apiProcessor , string basePath = "", string[] allowOrigins = null)
        {
            listener = new StreamSocketListener();
            port = serverPort;
            ApiProccessor = apiProcessor;

            if (allowOrigins != null)
            {
                var allowOriginsHeadersBuilder = new StringBuilder();
                foreach (var url in allowOrigins)
                {
                    allowOriginsHeadersBuilder.AppendFormat("Access-Control-Allow-Origin: {0}\r\n",url );  
                }

                allowOriginsHeadersBuilder.Append("Access-Control-Allow-Methods: GET\r\n");
                AllowOriginsHeader = allowOriginsHeadersBuilder.ToString();
            }
            else
            {
                AllowOriginsHeader = "Access-Control-Allow-Origin: *\r\n";
            }
            if (!string.IsNullOrWhiteSpace(basePath))
            {
                BasePath = basePath.Replace("\\", "/");
            }
            listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
        }
开发者ID:nSwann09,项目名称:Pi-WebLEDController,代码行数:27,代码来源:HttpServer.cs


示例9: Start

 /// <summary>
 /// 受付開始
 /// </summary>
 public async void Start()
 {
     listener = new StreamSocketListener();
     listener.ConnectionReceived += Listener_ConnectionReceived;
     // await listener.BindEndpointAsync(LOCALHOST, PORT.ToString());
     await listener.BindServiceNameAsync(PORT.ToString());
 }
开发者ID:moonmile,项目名称:winiot-samples,代码行数:10,代码来源:SimpleWebServer.cs


示例10: OnConnection

        /// <summary>
        /// Called when [connection].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="StreamSocketListenerConnectionReceivedEventArgs" /> instance containing the event data.</param>
        private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            StringBuilder request = new StringBuilder();
            try
            {
                // Get the whole request.
                using (IInputStream inputStream = args.Socket.InputStream)
                {
                    Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(BufferLength);
                    do
                    {
                        await inputStream.ReadAsync(buffer, BufferLength, InputStreamOptions.Partial);
                        request.Append(Encoding.UTF8.GetString(buffer.ToArray(), 0, (int)buffer.Length));
                    }
                    while (buffer.Length == BufferLength);
                }

                // Write the response.
                using (IOutputStream output = args.Socket.OutputStream)
                {
                    await output.WriteAsync(this.CreateResponse());
                }
            }
            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;
                }
            }
        }
开发者ID:gir,项目名称:RedditApi8,代码行数:37,代码来源:FakeHttpServer.cs


示例11: OnConnection

        private static async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            ConnectionStatus = ConnectionStatus.Connected;
            DataReader reader = new DataReader(args.Socket.InputStream);
            try
            {
                while (true)
                {
                    uint sizeFieldCount = await reader.LoadAsync(sizeof (uint));
                    if (sizeFieldCount != sizeof (uint))
                    {
                        return;
                    }
                    
                    uint stringLength = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);
                    if (stringLength != actualStringLength)
                    {
                        return;
                    }

                    Message = reader.ReadString(actualStringLength);
                }
            }
            catch (Exception e)
            {
                ConnectionStatus = ConnectionStatus.Failed;
                //TODO:send a connection status message with error
            }
        }
开发者ID:95strat,项目名称:GoPiGoWin10,代码行数:30,代码来源:SocketConnection.cs


示例12: RestServer

 public RestServer(int serverPort, AppServiceConnection connection)
 {
     listener = new StreamSocketListener();
     port = serverPort;
     appServiceConnection = connection;
     listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
 }
开发者ID:LeighCurran,项目名称:IoTExamples,代码行数:7,代码来源:RestServer.cs


示例13: Ctor_ServiceName

		public void Ctor_ServiceName()
		{
			const string serviceName = "monkeyService";
			var listener = new StreamSocketListener (serviceName);

			Assert.AreEqual (serviceName, listener.ServiceName);
		}
开发者ID:ermau,项目名称:WinRT.NET,代码行数:7,代码来源:StreamSocketListenerTests.cs


示例14: TcpServer_ConnectionReceived

 private void TcpServer_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     if (isRunning)
     {
         ClientAdded(this, new CustomEventArgs(args.Socket));
     }
 }
开发者ID:notdef1ned,项目名称:voice-chat-winrt,代码行数:7,代码来源:ChatServer.cs


示例15: Listener_ConnectionReceived

    private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
    {
        socket = args.Socket;
        var dr = new DataReader(socket.InputStream);

        /// GET ヘッダを取り出し
        StringBuilder request = new StringBuilder();
        uint BufferSize = 1024;
        using (IInputStream input = socket.InputStream)
        {
            byte[] data = new byte[BufferSize];
            IBuffer buffer = data.AsBuffer();
            uint dataRead = BufferSize;
            while (dataRead == BufferSize)
            {
                await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
                request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                dataRead = buffer.Length;
            }
        }
        // GET method を取り出し
        string requestMethod = request.ToString().Split('\n')[0];
        string[] requestParts = requestMethod.Split(' ');
        var text = requestParts[1];

        /// GETコマンドの受信イベント
        if (this.OnReceived != null)
        {
            OnReceived(text);
        }
    }
开发者ID:moonmile,项目名称:winiot-samples,代码行数:31,代码来源:SimpleWebServer.cs


示例16: HttpServer

 public HttpServer(int serverPort)
 {
     listener = new StreamSocketListener();
     port = serverPort;
     listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
     Debug.WriteLine("HttpServer Init");
 }
开发者ID:QQOak,项目名称:RoboComms,代码行数:7,代码来源:HttpServer.cs


示例17: HttpServer

 internal HttpServer(int serverPort)
 {
     _listener = new StreamSocketListener();
     _requestParser = new HttpRequestParser();
     _port = serverPort;
     _listener.ConnectionReceived += ProcessRequestAsync;
 }
开发者ID:Ferho,项目名称:restup,代码行数:7,代码来源:HttpServer.cs


示例18: listenButton_Click

        /// <summary>
        /// 服务器监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  async void listenButton_Click(object sender, RoutedEventArgs e)
        {
            if (listener != null)
            {
                await new MessageDialog("监听已经启动了").ShowAsync();
                return;
            }
            listener= new StreamSocketListener();
            //监听后连接的事件OnConnection
            listener.ConnectionReceived += OnConnection;
            //开始监听操作
            try
            {
                await listener.BindServiceNameAsync("22112");
                await new MessageDialog("正在监听").ShowAsync();
            }

            catch (Exception ex)
            {
                listener = null;
                //未知异常
                if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }
            }
        }
开发者ID:745322878,项目名称:Code,代码行数:32,代码来源:MainPage.xaml.cs


示例19: OnConnection

        private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {

            DataReader reader = new DataReader(args.Socket.InputStream);
            try
            {
                while (true)
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldCount != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Read the string.
                    uint stringLength = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);
                    if (stringLength != actualStringLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Display the string.
                    string text = reader.ReadString(actualStringLength);

                    string InLang = "en";
                    string outLang = "es-MX";
                    Translator Trans = new Translator(text, InLang, outLang);
                    string translatedS = Trans.GetTranslatedString();

                    SpeechSynthesisStream stream = await synthesizer.SynthesizeTextToStreamAsync(translatedS);
                    var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        media.SetSource(stream, stream.ContentType);
                        media.Play();
                        originalmsg.Text = text;
                        ReceivedText.Text = translatedS;
                        ReceivedText.FontSize = 20;
                    });
                }
            }
            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;
                }
                var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    StatusText.Text = "Error in Socket reading data from Remote host: " + exception.Message;
                    connected = false;
                    CoreApplication.Properties.Remove("clientSocket");
                    CoreApplication.Properties.Remove("clientDataWriter");
                });
            }
        }
开发者ID:dxmakers,项目名称:disrupt15,代码行数:60,代码来源:MainPage.xaml.cs


示例20: StartServer_Click_1

        private async void StartServer_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                if (listener == null)
                {
                    // We call it 'local', becuase if this connection doesn't succeed, we do not want
                    // to loose the possible previous conneted listener.
                    listener = new StreamSocketListener();

                    // ConnectionReceived handler must be set before BindServiceNameAsync is called, if not
                    // "A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)"
                    // error occurs.
                    listener.ConnectionReceived += OnConnectionReceived;

                    // Trying to bind more than once to the same port throws "Only one usage of each socket
                    // address (protocol/network address/port) is normally permitted. (Exception from
                    // HRESULT: 0x80072740)" exception.
                    await listener.BindServiceNameAsync("80");
                    DisplayOutput(TcpServerOutput, "Listening.");
                }
            }
            catch (Exception ex)
            {
                DisplayOutput(TcpServerOutput, ex.ToString());
            }
        }
开发者ID:kiewic,项目名称:Projects,代码行数:27,代码来源:MainPage.xaml.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# Credentials.PasswordVault类代码示例发布时间:2022-05-26
下一篇:
C# Sockets.StreamSocket类代码示例发布时间: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