Inheritance: IStreamSocketListener, IClosable
Exemplo n.º 1
0
        private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            var x = 0;
            var y = 0;

            using (var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
            {
                //DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedUser.GetType());
                //deserializedUser = ser.ReadObject(ms) as Coord;

                ////var coords = new (streamReader).Deserialize<Dictionary<string, Double>>;
                // x = coords["x"];
                // y = coords["y"];
                var ser = new JsonSerializer();

                using (var jsonTextReader = new JsonTextReader(streamReader))
                {
                    dynamic c = ser.Deserialize(jsonTextReader);
                    x = c.x;
                    y = c.y;
                }
            }

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.updateCoordinates(x, y));

            // Echo the request back as the response.
            sender.Dispose();

            // await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add("server closed its socket"));
        }
Exemplo n.º 2
0
 public HttpServer(int serverPort, StartupTask myTask)
 {
     listener = new StreamSocketListener();
     port = serverPort;
     listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
     startupTask = myTask;
 }
Exemplo n.º 3
0
 private void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     HasConnection = true;
     var socket = new ComplexStreamSocket(args.Socket);
     StartStreaming(socket);
     HasConnection = false;
 }
Exemplo n.º 4
0
        /// <summary>
        /// Initialize a server socket listening for incoming Bluetooth Rfcomm connections
        /// </summary>
        async void InitializeRfcommServer()
        {
            try
            {
                ListenButton.IsEnabled = false;
                DisconnectButton.IsEnabled = true;

                rfcommProvider = await RfcommServiceProvider.CreateAsync(
                    RfcommServiceId.FromUuid(RfcommChatServiceUuid));

                // Create a listener for this service and start listening
                socketListener = new StreamSocketListener();
                socketListener.ConnectionReceived += OnConnectionReceived;

                await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(),
                    SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                // Set the SDP attributes and start Bluetooth advertising
                InitializeServiceSdpAttributes(rfcommProvider);
                rfcommProvider.StartAdvertising(socketListener);

                NotifyStatus("Listening for incoming connections");
            }
            catch (Exception e)
            {
                NotifyError(e);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Server listens to specified port and accepts connection from client
        /// </summary>
        public async void StartListen()
        {
            var ip = (networkInterface != null)
                ? GetInterfaceIpAddress()
                : IPAddress.Any;

            tcpServer = new StreamSocketListener();
            await tcpServer.BindServiceNameAsync(portNumber.ToString());
            tcpServer.ConnectionReceived += TcpServer_ConnectionReceived;
            
            isRunning = true;
            // Keep accepting client connection
            while (isRunning)
            {
                if (!tcpServer.Pending())
                {
                    Thread.Sleep(500);
                    continue;
                }
                // New client is connected, call event to handle it
                var clientThread = new Thread(NewClient);
                var tcpClient = tcpServer.AcceptTcpClient();
                tcpClient.ReceiveTimeout = 20000;
                clientThread.Start(tcpClient.Client);
            }
        }
Exemplo n.º 6
0
        private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            double x            = 0;
            double y            = 0;
            var    streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead());
            var    ser          = new JsonSerializer();

            while (true)
            {
                var     jsonTextReader = new JsonTextReader(streamReader);
                dynamic c = ser.Deserialize(jsonTextReader);
                x = c.x * 50;
                y = c.y * 50;
                // updateCoordinates(x, y);
                Debug.WriteLine(x);
                Debug.WriteLine(y);
                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.updateCoordinates(x, y));
            }



            //await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.updateCoordinates(x, y));

            // Echo the request back as the response.
            //sender.Dispose();

            // await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add("server closed its socket"));
        }
Exemplo n.º 7
0
        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
            }
        }
Exemplo n.º 8
0
 public RestServer(int serverPort, AppServiceConnection connection)
 {
     listener = new StreamSocketListener();
     port = serverPort;
     appServiceConnection = connection;
     listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
 }
Exemplo n.º 9
0
        /// <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;
                }
            }
        }
Exemplo n.º 10
0
 public RestServer(int serverPort, string serviceConnection)
 {
     listener = new StreamSocketListener();
     port = serverPort;
     appServiceConnection = new AppServiceConnection() { AppServiceName = serviceConnection };
     listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
 }
Exemplo n.º 11
0
 private void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     if (this.OnConnectionReceived != null)
     {
         this.OnConnectionReceived(args.Socket);
     }
 }
Exemplo n.º 12
0
		public void Ctor_ServiceName()
		{
			const string serviceName = "monkeyService";
			var listener = new StreamSocketListener (serviceName);

			Assert.AreEqual (serviceName, listener.ServiceName);
		}
Exemplo n.º 13
0
        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);
        }
Exemplo n.º 14
0
        public async void Star()
        {
            try
            {
                //Fecha a conexão com a porta que está escutando atualmente
                if (listener != null)
                {
                    await listener.CancelIOAsync();
                    listener.Dispose();
                    listener = null;
                }

                //Criar uma nova instancia do listerner
                listener = new StreamSocketListener();

                //Adiciona o evento de conexão recebida ao método Listener_ConnectionReceived
                listener.ConnectionReceived += Listener_ConnectionReceived;
                //Espera fazer o bind da porta
                await listener.BindServiceNameAsync(Port.ToString());
            }
            catch (Exception e)
            {
                //Caso aconteça um erro, dispara o evento de erro
                if (OnError != null)
                    OnError(e.Message);
            }
        }
Exemplo n.º 15
0
 private async void TcpServer_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     if (isRunning)
     {
         await ThreadPool.RunAsync(new WorkItemHandler((IAsyncResult) => AddClient(args)));
     }
 }
Exemplo n.º 16
0
 internal HttpServer(int serverPort)
 {
     _listener = new StreamSocketListener();
     _requestParser = new HttpRequestParser();
     _port = serverPort;
     _listener.ConnectionReceived += ProcessRequestAsync;
 }
Exemplo n.º 17
0
        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");
                });
            }
        }
Exemplo n.º 18
0
    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);
        }
    }
Exemplo n.º 19
0
        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());
            }
        }
Exemplo n.º 20
0
 private void TcpServer_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     if (isRunning)
     {
         ClientAdded(this, new CustomEventArgs(args.Socket));
     }
 }
Exemplo n.º 21
0
        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());
            }
        }
Exemplo n.º 22
0
        /// <summary>
        ///     Binds the <code>TcpSocketListener</code> to the specified port on all endpoints and listens for TCP connections.
        /// </summary>
        /// <param name="port">The port to listen on. If '0', selection is delegated to the operating system.</param>
        /// <param name="listenOn">The <code>CommsInterface</code> to listen on. If unspecified, all interfaces will be bound.</param>
        /// <returns></returns>
        public Task StartListeningAsync(int port, ICommsInterface listenOn = null)
        {
            if (listenOn != null && !listenOn.IsUsable)
                throw new InvalidOperationException("Cannot listen on an unusable interface. Check the IsUsable property before attemping to bind.");
            
            _listenCanceller = new CancellationTokenSource();
            _backingStreamSocketListener = new StreamSocketListener();

            _backingStreamSocketListener.ConnectionReceived += (sender, args) =>
            {
                var nativeSocket = args.Socket;
                var wrappedSocket = new TcpSocketClient(nativeSocket, _bufferSize);

                var eventArgs = new TcpSocketListenerConnectEventArgs(wrappedSocket);
                if (ConnectionReceived != null)
                    ConnectionReceived(this, eventArgs);
            };

            var sn = port == 0 ? "" : port.ToString();
#if !WP80    
            if (listenOn != null)
            {
                var adapter = ((CommsInterface)listenOn).NativeNetworkAdapter;

                return _backingStreamSocketListener
                            .BindServiceNameAsync(sn, SocketProtectionLevel.PlainSocket, adapter)
                            .AsTask();
            }
            else
#endif
                return _backingStreamSocketListener
                            .BindServiceNameAsync(sn)
                            .AsTask();
        }
Exemplo n.º 23
0
        private async void ProcessRequestAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            await Task.Run(async () =>
            {
                try
                {
                    using (var inputStream = args.Socket.InputStream)
                    {
                        var request = await HttpServerRequest.Parse(inputStream);

                        var httpResponse = await HandleRequest(request);

                        await WriteResponseAsync(httpResponse, args.Socket);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Exception while handling process: {ex.Message}");
                }
                finally
                {
                    try
                    {
                        args.Socket.Dispose();
                    }
                    catch { }
                }
            });
        }
Exemplo n.º 24
0
 /// <summary>
 /// 受付開始
 /// </summary>
 public async void Start()
 {
     listener = new StreamSocketListener();
     listener.ConnectionReceived += Listener_ConnectionReceived;
     // await listener.BindEndpointAsync(LOCALHOST, PORT.ToString());
     await listener.BindServiceNameAsync(PORT.ToString());
 }
Exemplo n.º 25
0
        /// <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;
                }
            }
        }
Exemplo n.º 26
0
 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();
             });
     }
 }
Exemplo n.º 27
0
 public HttpServer(int serverPort)
 {
     listener = new StreamSocketListener();
     port = serverPort;
     listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
     Debug.WriteLine("HttpServer Init");
 }
Exemplo n.º 28
0
    private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
    {
        string request = "";

        using (var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
        {
            using (Stream outputStream = args.Socket.OutputStream.AsStreamForWrite())
            {
                using (var streamWriter = new StreamWriter(outputStream))
                {
                    await SendMessage(streamWriter, "localhost");

                    while (request.ToLower() != "exit")
                    {
                        request = await streamReader.ReadLineAsync();

                        PlayerPrefs.SetString("host", request);
                        PlayerPrefs.Save();
                        await SendMessage(streamWriter, request);
                    }
                }
            }
        }

        sender.Dispose();
        serverStatus = ServerStatus.Stopped;
    }
Exemplo n.º 29
0
        private async Task run(string host, int port)
        {
            var listener = new StreamSocketListener();
            listener.ConnectionReceived += listener_ConnectionReceived;

            await listener.BindEndpointAsync(new HostName(host), port.ToString());
        }
Exemplo n.º 30
0
        public async void Start()
        {
            this.listener = new StreamSocketListener();
            this.listener.ConnectionReceived += Listener_ConnectionReceived;

            await listener.BindServiceNameAsync(this.port.ToString());
        }
Exemplo n.º 31
0
    // Use this for initialization
#if !WINDOWS_UWP
    void Start()
    {
#endif
#if WINDOWS_UWP
    async void Start()
    {
        try
        {
            socketListener = new Windows.Networking.Sockets.StreamSocketListener();
            socketListener.ConnectionReceived += SocketListener_ConnectionReceived;
            await socketListener.BindServiceNameAsync("1337");
        }
        catch (Exception e)
        {
            counttext.text = "Error: " + e.ToString();
        }
#endif
    }


    // Update is called once per frame
    void Update () {
        missiontext.text = "Prepare to shoot! 20 of 30";
        counttext.text = "Count down: 2";
        errortext.text = "Connected!";
        progressbar.value = ToSingle(0.66);
        if (!request.Equals("Request not received yet"))
        {
            errortext.text = request;
        }
	}
 // private AppServiceConnection appServiceConnection;
 public TinyHttpdServer(int serverPort)
 {
     listener = new StreamSocketListener();
     port = serverPort;
     listener.ConnectionReceived += (s, e) =>
                     ProcessRequestAsync(e.Socket);
 }
Exemplo n.º 33
0
        private async void SocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender,
                                                             Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            UnityClient.Instance.SetConnection(args);
            // CoreApplication.Properties.Add("listener", uClient);
            //Read line from the remote client.
            while (true)
            {
                Stream       inStream = args.Socket.InputStream.AsStreamForRead();
                StreamReader reader   = new StreamReader(inStream);
                string       request  = string.Empty;
                try
                {
                    request = await reader.ReadLineAsync();

                    System.Diagnostics.Debug.WriteLine("TurdServer::SocketListener::request " + request);
                    HandleCommand(request);
                }
                catch (Exception ex)
                {
                    UnityClient.Instance.ClearConnection();
                    System.Diagnostics.Debug.WriteLine("Client disconnected." + ex.Message);
                    break;
                }

                //Send the line back to the remote client.
                //Stream outStream = args.Socket.OutputStream.AsStreamForWrite();
                //StreamWriter writer = new StreamWriter(outStream);
                //await writer.WriteLineAsync(request);
                //await writer.FlushAsync();
            }
        }
Exemplo n.º 34
0
        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());
            }
        }
Exemplo n.º 35
0
        private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            string request;

            using (var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
            {
                request = await streamReader.ReadLineAsync();
            }

            Debug(string.Format("server received the request: \"{0}\"", request));

            /*
             *         // Echo the request back as the response.
             * using (Stream outputStream = args.Socket.OutputStream.AsStreamForWrite())
             * {
             *  using (var streamWriter = new StreamWriter(outputStream))
             *  {
             *      await streamWriter.WriteLineAsync(request);
             *      await streamWriter.FlushAsync();
             *  }
             * }
             *
             * Debug(string.Format("server sent back the response: \"{0}\"", request));
             *
             * sender.Dispose();
             */
            Debug("server closed its socket");
        }
Exemplo n.º 36
0
        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);
            }
        }
        private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            string request;

            using (var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
            {
                request = await streamReader.ReadLineAsync();
            }

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add(string.Format("server received the request: \"{0}\"", request)));

            // Echo the request back as the response.
            using (Stream outputStream = args.Socket.OutputStream.AsStreamForWrite())
            {
                using (var streamWriter = new StreamWriter(outputStream))
                {
                    await streamWriter.WriteLineAsync(request);

                    await streamWriter.FlushAsync();
                }
            }

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add(string.Format("server sent back the response: \"{0}\"", request)));

            sender.Dispose();

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add("server closed its socket"));
        }
Exemplo n.º 38
0
 private async void SocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, 
                                                         Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
 {
     //Read line from the remote client.
     Stream inStream = args.Socket.InputStream.AsStreamForRead();
     StreamReader reader = new StreamReader(inStream);
     request = await reader.ReadLineAsync();
 }
Exemplo n.º 39
0
    private async void Socket_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender,
                                                 Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
    {
        Debug.Log("received connection");
        streamSocket = args.Socket;

        connectedEstablished = true;
    }
Exemplo n.º 40
0
        private async System.Threading.Tasks.Task CreateServerAsync()
        {
            try
            {
                socketListener = new Windows.Networking.Sockets.StreamSocketListener();
                socketListener.ConnectionReceived += SocketListener_ConnectionReceived;

                await socketListener.BindServiceNameAsync("1337");
            }
            catch (Exception e)
            {
                Log.Error("Create Server On Port 1337 Error", e);
            }
        }
Exemplo n.º 41
0
        private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            streamSocket = args.Socket;
            //await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add("Hololens Connected"));

            using (streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
            {
                request = await streamReader.ReadLineAsync();
            }

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add("Hololens Connected"));

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add("Hololens sent: " + request));

            if (request == "On")
            {
                _turnOnIgnition();
            }

            if (request == "Forwards")
            {
                _forwardMotor();
            }

            else if (request == "Backwards")
            {
                _reverseMotor();
            }

            else if (request == "Left")
            {
                _turnLeft();
            }

            else if (request == "Right")
            {
                _turnRight();
            }

            else if (request == "Stop")
            {
                _stopMotor();
            }

            else if (request == "Off")
            {
                _turnOffIgnition();
            }
        }
Exemplo n.º 42
0
    private async void StartServer()
    {
        try
        {
            var streamSocketListener = new Windows.Networking.Sockets.StreamSocketListener();

            // The ConnectionReceived event is raised when connections are received.
            streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;

            // Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use.
            await streamSocketListener.BindServiceNameAsync(PortNumber);

            serverStatus = ServerStatus.Started;
        }
        catch (Exception ex)
        {
            Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
        }
    }
        private async void StartServer()
        {
            try
            {
                var streamSocketListener = new Windows.Networking.Sockets.StreamSocketListener();

                // The ConnectionReceived event is raised when connections are received.
                streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;

                // Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use.
                await streamSocketListener.BindServiceNameAsync(StreamSocketAndListenerPage.PortNumber);

                this.serverListBox.Items.Add("server is listening...");
            }
            catch (Exception ex)
            {
                Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
                this.serverListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
            }
        }
Exemplo n.º 44
0
    private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
    {
        string request;

        Debug.Log("reading stream.....");

        var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead(), System.Text.Encoding.UTF8, true, 1024, true);

        request = await streamReader.ReadLineAsync();

        clientAddress = request;

        Debug.Log(string.Format("server received the request: \"{0}\"", request));

        // Echo the request back as the response.

        outStream = args.Socket.OutputStream;

        Debug.Log(string.Format("server sent back the response: \"{0}\"", request));

        Debug.Log("server closed its socket");
    }
Exemplo n.º 45
0
    // Use this for initialization
#if !WINDOWS_UWP
    void Start()
    {
#endif
#if WINDOWS_UWP
    async void Start()
    {
        try
        {
            socketListener = new Windows.Networking.Sockets.StreamSocketListener();
            socketListener.ConnectionReceived += SocketListener_ConnectionReceived;
            await socketListener.BindServiceNameAsync("1337");
        }
        catch (Exception e)
        {
            counttext.text = "Error: " + e.ToString();
        }
#endif
    }

    void Update()
    {
        errortext.text = request + " " + hand.transform.localEulerAngles.y;
        float a = 0;
        missiontext.text = "Request not received yet";
        /*if (!request.Equals("Request not received yet")) {
            if (Tutorialed == false) {
                missiontext.text = "Keep using your maximum strength. Tutorial Part";
                double tutorial = Double.Parse(request);
                if (Time.deltaTime > 1 && Time.deltaTime < 5)
                {
                    errortext.text = " " + Time.deltaTime + "  : Tutorial Part";
                    counttext.text = (5 - Time.deltaTime) + " seconds left in tutorial part";
                    if (EMGMaximum < tutorial)
                    {
                        EMGMaximum = tutorial;
                    }
                }
                Tutorialed = true;
                startgametime = Time.deltaTime;
            }
            if (Tutorialed == true) {
                {
                    try
                    {
                        double data = Double.Parse(request);

                        if ((Time.time - startgametime) % 10 < 2 && ((Time.time - startgametime)) < 300)
                        {
                            missiontext.text = "Prepare to shoot in 2 seconds.";
                            counttext.text = "Count down " + (2 - (Time.time - startgametime) % 10);
                        }
                        if (((Time.time - startgametime) % 10) >= 2 && ((Time.time - startgametime) % 10) < 5 && ((Time.time - startgametime)) < 300)
                        {
                            missiontext.text = "Use your MAXIMUM strength now~";
                            counttext.text = "Count down " + (5 - (Time.time - startgametime) % 10);
                            Progressslide.value += ToSingle(0.03);
                            if (data > EMGtemp)
                            {
                                EMGtemp = data;
                            }
                            if (data > EMGMaximum)
                            {
                                EMGMaximum = data;
                            }
                        }
                        if (((Time.time - startgametime) % 10) >= 5 && ((Time.time - startgametime) % 10) < 10 && ((Time.time - startgametime)) < 300 && ((Time.time - startgametime)) > nextFire)
                        {
                            missiontext.text = "Shooting";
                            counttext.text = "Count down " + (10 - (Time.time - startgametime) % 10);
                            nextFire = ToSingle(Time.time - startgametime) + fireRate;
                            if (EMGtemp > EMGMaximum * 0.8)
                            {
                                ThrowNewBallSuccess();
                                Success = Success + 1;
                            }
                            if (EMGtemp <= EMGMaximum * 0.8)
                            {
                                ThrowNewBallFail();
                            }

                            if ((hand.transform.localEulerAngles.y <= 50 && hand.transform.localEulerAngles.y >= 0) ||
                                (hand.transform.localEulerAngles.y >= 300 && hand.transform.localEulerAngles.y <= 360))
                            {
                                hand.transform.Rotate(0.0f, a + (float)EMGtemp, 0.0f);
                            }
                            else
                            {
                                if (hand.transform.localEulerAngles.y > 50 && hand.transform.localEulerAngles.y < 180)
                                {
                                    hand.transform.localEulerAngles = new Vector3(

                                        0.0f,
                                        50f,
                                        0.0f
                                    );
                                }

                                if (hand.transform.localEulerAngles.y < 300 && hand.transform.localEulerAngles.y > 180)
                                {
                                    hand.transform.localEulerAngles = new Vector3(
                                        0.0f,
                                        300f,
                                        0.0f
                                        );
                                }
                            }
                        }

                        else if ((Time.time - startgametime) >= 300)
                        {
                            missiontext.text = "CONGRATULATIONS! You shot " + Success + " out of 30 balls!";
                            counttext.text = "Thank you for playing";
                            Progressslide.value = 1;
                        }
                    }

                    catch (Exception e) {
                        errortext.text = "Error: " + e.ToString();
                    }
                }


                a = hand.transform.localEulerAngles.y;
            }
        }
        */
    }