Example #1
0
        /// <summary>
        /// A listener object that responds when ever there has been a connection established
        /// </summary>
        /// <param name="sender">
        ///
        /// </param>
        /// <param name="args">
        ///
        /// </param>
        private async void 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();
            }

            this.Output(MessageHelper.MessageType.Data, request);

            // if responder exists then respond else don't bother
            if (responderObject != null)
            {
                // deal with the responce appropriately
                string responce = responderObject.Respond(ref request);

                using (var streamWriter = new StreamWriter(args.Socket.OutputStream.AsStreamForWrite()))
                {
                    // call the responder object and send back the responce
                    streamWriter.WriteLine(responce);

                    // output the message to the helper if it exists
                    this.Output(MessageHelper.MessageType.Status, string.Format("server acted on the response: \"{0}\" appropiatly", responce));
                }
            }
        }
        /// <summary>
        /// Event handler for handling incoming connections and save the mesh data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            using (var stream = args.Socket.InputStream.AsStreamForRead())
            {
                // TODO Make sure there is data in the stream.

                // The first 4 bytes will be the size of the data containing the mesh(es).
                int datasize = ReadInt(stream);

                // Allocate a buffer to hold the data.
                byte[] dataBuffer = new byte[datasize];

                // Read the data.
                // The data can come in chunks.
                int readsize = 0;

                while (readsize != datasize)
                {
                    readsize += stream.Read(dataBuffer, readsize, datasize - readsize);
                }

                System.Diagnostics.Debug.WriteLine("Received:" + datasize + "bytes");

                ReceivedMeshes.Enqueue(dataBuffer);
            }
        }
Example #3
0
        public override void    StopServer()
        {
            if (this.tcpListener != null)
            {
                this.BroadcastPacket(new ServerHasDisconnectedPacket());

                for (int i = 0; i < this.clients.Count; i++)
                {
                    if (this.DetectClientDisced(this.clients[i]) == true)
                    {
                        this.clients[i].Close();
                        this.clients.RemoveAt(i);
                        --i;
                        continue;
                    }

                    this.clients[i].Write(this.server.executer);
                }

#if NETFX_CORE
                this.tcpListener.Dispose();
#else
                this.tcpListener.Server.Close();
#endif
                this.tcpListener = null;

                InternalNGDebug.LogFile("Stopped AbstractTcpListener.");
            }
        }
Example #4
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();
            }

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>

                                           ShowMessage(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, () => ShowMessage(string.Format("server sent back the response: \"{0}\"", request)));

            sender.Dispose();

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => ShowMessage("server closed its socket"));
        }
Example #5
0
        private async System.Threading.Tasks.Task MakeDiscoverable()
        {
            // Make the system discoverable. Don'd repeatedly do this or the StartAdvertising will throw "cannot create a file when that file already exists"
            if (!App.IsBluetoothDiscoverable)
            {
                Guid BluetoothServiceUuid = new Guid("17890000-0068-0069-1532-1992D79BE4D8");
                try
                {
                    provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(BluetoothServiceUuid));

                    Windows.Networking.Sockets.StreamSocketListener listener = new Windows.Networking.Sockets.StreamSocketListener();
                    listener.ConnectionReceived += OnConnectionReceived;
                    await listener.BindServiceNameAsync(provider.ServiceId.AsString(), Windows.Networking.Sockets.SocketProtectionLevel.PlainSocket);

                    //     SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
                    // Don't bother setting SPD attributes
                    provider.StartAdvertising(listener, true);
                    App.IsBluetoothDiscoverable = true;
                }
                catch (Exception e)
                {
                    string formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothNoDeviceAvailableFormat");
                    string confirmationMessage = string.Format(formatString, e.Message);
                    DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);
                }
            }
        }
 private void DoStopAdvertising()
 {
     if (_listener != null)
     {
         _provider.StopAdvertising();
         _listener.ConnectionReceived -= _listener_ConnectionReceived;
         _listener = null;
     }
 }
Example #7
0
 public TCPListener(ISoccerBotLogger logger, Server server, int port)
 {
     _server = server;
     _logger = logger;
     _port   = port;
     _logger.NotifyUserInfo("TCPIP Listener", $"Created Listener");
     _listener = new Windows.Networking.Sockets.StreamSocketListener();
     _listener.ConnectionReceived += _listener_ConnectionReceived;
 }
 private void DoStartAdvertising()
 {
     if (_listener == null)
     {
         _listener = new Windows.Networking.Sockets.StreamSocketListener();
         _listener.ConnectionReceived += _listener_ConnectionReceived;
         _provider.StartAdvertising(_listener);
     }
 }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var streamSocketListener = new Windows.Networking.Sockets.StreamSocketListener();

            streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;
            await streamSocketListener.BindServiceNameAsync("1337");

            var streamSocket = new Windows.Networking.Sockets.StreamSocket();
            await streamSocket.ConnectAsync(new Windows.Networking.HostName("localhost"), "1337");

            this.SendMultipleBuffersInefficiently(streamSocket, "Hello, World!");
            //this.BatchedSendsCSharpOnly(streamSocket, "Hello, World!");
            //this.BatchedSendsAnyUWPLanguage(streamSocket, "Hello, World!");
        }
Example #10
0
        private void SocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender,
                                                       Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Debug.WriteLine("connessione ricevuta");

            //Read line from the remote client.
            Stream inStream = args.Socket.InputStream.AsStreamForRead();

            outStream = args.Socket.OutputStream.AsStreamForWrite();

            msgCount = 0;
            int          byteCount = 0;
            BinaryReader reader    = new BinaryReader(inStream);
            Boolean      connOn    = true;

            while (connOn)
            {
                try
                {
                    byte request = reader.ReadByte();
                    byteCount++;
                    string hexOutput = String.Format("{0:X2}", request);
                    Debug.Write(hexOutput);

                    //await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                    //() =>
                    //{
                    //    textBlock.Text += hexOutput;
                    //});

                    if (byteCount == msgLenght[msgCount])
                    {
                        byteCount = 0;
                        msgSend();
                        if (msgCount < 3)
                        {
                            msgCount++;
                        }
                    }
                }
                catch
                {
                    Debug.WriteLine("Remote host closed connection");
                    connOn = false;
                }
            }
        }
Example #11
0
        private async void      OnConnection(Windows.Networking.Sockets.StreamSocketListener sender,
                                             Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Debug.LogError("New client" + sender.Information.LocalPort);

            var reader = new Windows.Storage.Streams.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 on the screen. The event is invoked on a non-UI thread, so we need to marshal
                    // the text back to the UI thread.
                    //NotifyUserFromAsyncThread(
                    //	String.Format("Received data: \"{0}\"", reader.ReadString(actualStringLength)),
                    //	NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (Windows.Networking.Sockets.SocketError.GetStatus(ex.HResult) == Windows.Networking.Sockets.SocketErrorStatus.Unknown)
                {
                    throw;
                }
            }
        }
        public 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);
            }
            catch (Exception ex)
            {
                Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
            }
        }
Example #13
0
        /// <summary>
        /// trys to read a string from the socket and send it back
        /// </summary>
        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);
            string       request  = await reader.ReadLineAsync();

            Debug.WriteLine("request: " + request);

            //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();
        }
Example #14
0
        private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            using (var dataReader = new DataReader(args.Socket.InputStream))
            {
                dataReader.InputStreamOptions = InputStreamOptions.Partial;
                while (true)
                {
                    await dataReader.LoadAsync(256);

                    if (dataReader.UnconsumedBufferLength == 0)
                    {
                        break;
                    }
                    IBuffer requestBuffer = dataReader.ReadBuffer(dataReader.UnconsumedBufferLength);
                    string  request       = Windows.Security.Cryptography.CryptographicBuffer.ConvertBinaryToString(Windows.Security.Cryptography.BinaryStringEncoding.Utf8, requestBuffer);
                    Debug.WriteLine(string.Format("server received the request: \"{0}\"", request));
                }
            }
        }
Example #15
0
        public async void CreateSocketListener()
        {
            try
            {
                // Create a StreamSocketListener to start listening for TCP connections.
                socketListener = new Windows.Networking.Sockets.StreamSocketListener();

                // Hook up an event handler to call when connections are received.
                socketListener.ConnectionReceived += SocketListener_ConnectionReceived;

                // Start listening for incoming TCP connections on the specified port. You can specify any port that' s not currently in use.
                await socketListener.BindServiceNameAsync(portNum);
            }
            catch (Exception e)
            {
                Debug.WriteLine("CreateSocketListener() fault...");
                // Handle exception.
            }
        }
        /// <summary>
        /// Used to start the stream socket listener and attach the event handler for incoming connections
        /// </summary>
        private async void StartServer()
        {
            try
            {
                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(ConnectionPort.ToString());

                System.Diagnostics.Debug.WriteLine("Listener started on port " + ConnectionPort);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Couldn't open socket listener.");
            }
        }
Example #17
0
        private async void StartServer()
        {
            try
            {
                var streamSocketListener = new Windows.Networking.Sockets.StreamSocketListener();

                // The ConnectionReceived event is raised when connections are received.
                streamSocketListener.ConnectionReceived += 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(PortBox.Text);

                ShowMessage("server is listening...");
            }
            catch (Exception ex)
            {
                Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
                ShowMessage(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
            }
        }
Example #18
0
        /// <summary>
        /// creates TCP socket that is listening on port 7777 for requests
        /// requests will be handeled by SocketListener_ConnectionReceived
        /// </summary>
        private async Task createListenerAsync()
        {
            //Create a StreamSocketListener to start listening for TCP connections.
            Windows.Networking.Sockets.StreamSocketListener socketListener = new Windows.Networking.Sockets.StreamSocketListener();

            //Hook up an event handler to call when connections are received.
            socketListener.ConnectionReceived += SocketListener_ConnectionReceived;
            Debug.WriteLine("create Listener");

            try
            {
                //Start listening for incoming TCP connections on the specified port
                await socketListener.BindServiceNameAsync("7777");

                Debug.WriteLine("created Listener");
            }
            catch (Exception e)
            {
                //Handle exception.
            }
        }
Example #19
0
        private async void SocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender,
                                                             Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            // Read line from the remote client.
            inStream     = args.Socket.InputStream.AsStreamForRead();
            streamReader = new StreamReader(inStream);
            // Add timeout function (ms)
            // streamReader.BaseStream.ReadTimeout = 3000;

            string request = await streamReader.ReadLineAsync();

            try
            {
                await CheckCommand(request, args);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Command Execution Fault...");
                Debug.WriteLine(e);
            }
        }
Example #20
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Debug.WriteLine("provo a connettermi");
                //Create a StreamSocketListener to start listening for TCP connections.
                Windows.Networking.Sockets.StreamSocketListener socketListener = new Windows.Networking.Sockets.StreamSocketListener();

                //Hook up an event handler to call when connections are received.
                socketListener.ConnectionReceived += SocketListener_ConnectionReceived;

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

                Debug.WriteLine("connesso");
            }
            catch (Exception er)
            {
                Debug.WriteLine("ops...");
                Debug.WriteLine(er.Message);
            }
        }
        private async Task StartServer()
        {
            try
            {
                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(SocketServerTerminalPage.PortNumber);

                //_Mode = Mode.JustConnected;

                status.Text = "Server is listening...";
            }
            catch (Exception ex)
            {
                Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
                status.Text = webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message;
            }
        }
Example #22
0
        /// <summary>
        /// Start the server and collect and respond to any incoming streams
        /// </summary>
        public void Start()
        {
            try
            {
                streamSocketListener = new Windows.Networking.Sockets.StreamSocketListener();

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

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

                this.Output(MessageHelper.MessageType.Status, "server is listening on port \"" + this.portNumber + "\"");
            }
            catch (Exception ex)
            {
                // Lots of scary looking code here :/
                // all that it says below is if you don't know what is going on write to buffer
                Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
                this.Output(MessageHelper.MessageType.Exception, webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
            }
        }
        public 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();
            }

            Message = 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();
            //    }
            //}

            sender.Dispose();
        }
Example #24
0
 /// <summary>
 /// We have to have a callback handler to handle "ConnectionReceived" but we don't do anything because
 /// the StartAdvertising is just a way to turn on Bluetooth discoverability
 /// </summary>
 /// <param name="listener"></param>
 /// <param name="args"></param>
 void OnConnectionReceived(Windows.Networking.Sockets.StreamSocketListener listener,
                           Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
 {
 }
Example #25
0
 public async Task StartListeningAsync()
 {
     _listener = new Windows.Networking.Sockets.StreamSocketListener();
     _listener.ConnectionReceived += _listener_ConnectionReceived;
     await _listener.BindServiceNameAsync(_listenPort.ToString());
 }
Example #26
0
 private void _listener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
 {
     _connection.Open(args.Socket);
 }
        private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            //string request="";
            string response;

            char[] chars = new char[10];
            chars[1] = 'Z';
            int  responseLength;
            byte cFineStructureConstant = 137;

            try
            {
                using (var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
                {
                    using (Stream outputStream = args.Socket.OutputStream.AsStreamForWrite())
                    {
                        using (var streamWriter = new StreamWriter(outputStream))
                        {
                            if (_Mode == Mode.Disconnected)
                            {
                                response = await streamReader.ReadLineAsync();

                                await streamWriter.WriteLineAsync("Hello World");

                                await streamWriter.FlushAsync();

                                await streamWriter.WriteAsync('@');

                                await streamWriter.FlushAsync();

                                //Once the first transmission/s, iniitaited from thsi end, is received then this end IS connected.
                                _Mode = Mode.Connected;


                                responseLength = await streamReader.ReadAsync(chars, 0, 10);

                                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => recvdText.Text = "" + chars);

                                if (chars[0] == '0')
                                {
                                    await streamWriter.WriteAsync('1');

                                    await streamWriter.FlushAsync();
                                }
                                _Mode = Mode.ACK0;


                                responseLength = await streamReader.ReadAsync(chars, 0, 10);

                                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => recvdText.Text = "" + chars[0]);

                                if (chars[0] == '2')
                                {
                                    await streamWriter.WriteAsync('3');

                                    await streamWriter.FlushAsync();
                                }

                                _Mode = Mode.ACK2;

                                responseLength = await streamReader.ReadAsync(chars, 0, 10);

                                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => recvdText.Text = "" + chars[0]);

                                if (chars[0] == '4')
                                {
                                    await streamWriter.WriteAsync('5');

                                    await streamWriter.FlushAsync();
                                }
                                _Mode = Mode.ACK4;

                                responseLength = await streamReader.ReadAsync(chars, 0, 10);

                                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => recvdText.Text = "" + chars[0]);

                                if (chars[0] == '!')
                                {
                                    await streamWriter.WriteAsync('/');

                                    await streamWriter.FlushAsync();
                                }

                                _Mode = Mode.Ready;


                                responseLength = await streamReader.ReadAsync(chars, 0, 1);

                                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => recvdText.Text = "" + chars[0]);

                                if (chars[0] == '/')
                                {
                                    _Mode = Mode.Json1;
                                    await streamWriter.WriteLineAsync(
                                        "{\"Config\":[ [ { \"iWidth\": 120 },{ \"iHeight\": 100 },{ \"iSpace\": 5 },{ \"iCornerRadius\": 10 },{ \"iRows\": 2 },{ \"iColumns\": 5 },{ \"sComPortId\": \"\\\\\\\\?\\\\USB#VID_26BA&PID_0003#5543830353935161A112#{86e0d1e0-8089-11d0-9ce4-08003e301f73}\" },{ \"sFTDIComPortId\": \"\\\\\\\\?\\\\FTDIBUS#VID_0403+PID_6001+FTG71BUIA#0000#{86e0d1e0-8089-11d0-9ce4-08003e301f73}\" },{ \"iComportConnectDeviceNo\": -1 },{ \"iFTDIComportConnectDeviceNo\": 1 },{ \"sUseSerial\": \"BT\" } ] ] }~");

                                    await streamWriter.FlushAsync();

                                    responseLength = await streamReader.ReadAsync(chars, 0, 1);

                                    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => recvdText.Text = "" + chars[0]);

                                    {
                                        if (chars[0] == '~')
                                        {
                                            _Mode = Mode.Json2;
                                            await streamWriter.WriteLineAsync(
                                                "{\"MainMenu\":[ [ \"Something else\", \"Unload\", \"Show full list\", \"Setup Sockets\", \"The quick brown fox jumps over the lazy dog\" ],[ \"First\", \"Back\", \"Next\", \"Last\", \"Show All\" ] ] }~");

                                            await streamWriter.FlushAsync();

                                            _Mode = Mode.Running;
                                        }
                                        ;
                                    }
                                }

                                bool listening = true;
                                _Mode = Mode.Running;
                                while (listening)
                                {
                                    try
                                    {
                                        responseLength = await streamReader.ReadAsync(chars, 0, 1);
                                    }
                                    catch (Exception ex)
                                    {
                                        await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => status.Text += "\r\n" + "Lost connection:\r\n" + ex.Message);

                                        listening = false;
                                    }

                                    if (listening)
                                    {
                                        switch (chars[0])
                                        {
                                        case '^':
                                            listening = false;
                                            break;

                                        default:
                                            //Do app stuff here. For now just echo chars sent
                                            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => status.Text += "" + chars[0]);

                                            try
                                            {
                                                await streamWriter.WriteAsync(chars[0]);

                                                await streamWriter.FlushAsync();
                                            }
                                            catch (Exception ex)
                                            {
                                                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => status.Text += "\r\n" + "Lost connection:\r\n" + ex.Message);

                                                listening = false;
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => status.Text += "\r\n" + "Lost connection:\r\n" + ex.Message);
            }

            //await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => status.Text = string.Format("server sent back the response: \"{0}\"", request));
            sender.Dispose();

            //await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => status.Text = "server closed its socket"); ;
        }
Example #28
0
 private void _listener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
 {
     _server.ClientConnected(args.Socket);
 }
        public void StartListening()
        {
            // Data buffer for incoming data.
            byte[] info = new Byte[1];

            // Establish the local endpoint for the socket.
            // Dns.GetHostName returns the name of the
            // host running the application.
            IPHostEntry ipHostInfo = Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult();
            IPAddress   ipAddress  = ipHostInfo.AddressList[1];

            Debug.WriteLine(ipAddress.ToString());
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 2001);

            // Create a TCP/IP socket.
            Socket listener = new Socket(ipAddress.AddressFamily,
                                         SocketType.Stream, ProtocolType.Tcp);

            Windows.Networking.Sockets.StreamSocketListener socket = new Windows.Networking.Sockets.StreamSocketListener();
            Windows.Networking.HostName hostName = new Windows.Networking.HostName("192.168.1.105");


            int rec_flag = 0;
            int i        = 0;

            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(2);
                motor.StartLeds();
                // Start listening for connections.
                while (true)
                {
                    Debug.WriteLine("Waiting for a connection...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler  = listener.AcceptAsync().GetAwaiter().GetResult();
                    string exitData = "";
                    Debug.WriteLine("Accepted connection");
                    info = null;

                    // An incoming connection needs to be processed.
                    while (true)
                    {
                        info = new byte[1];
                        int bytesRec = handler.Receive(info);

                        string data = string.Concat(info.Select(b => b.ToString("X2")).ToArray());//Encoding.ASCII.GetString(bytes, 0, bytesRec);

                        Debug.WriteLine("data: " + data);
                        if (data == "00")
                        {
                            exitData += data;
                        }
                        else
                        {
                            exitData = "";
                        }
                        if (exitData == "00000000")
                        {
                            break;
                        }

                        if (rec_flag == 0)
                        {
                            if (data == "FF")
                            {
                                buffer   = "";
                                rec_flag = 1;
                                i        = 0;
                            }
                        }
                        else
                        {
                            if (data == "FF")
                            {
                                rec_flag = 0;
                                if (i == 3)
                                {
                                    Debug.WriteLine("Got data " + data);
                                    Communication_Decode();
                                }
                                i = 0;
                            }
                            else
                            {
                                buffer += data;
                                i      += 1;
                            }
                        }
                    }

                    // Show the data on the console.
                    Debug.WriteLine("Text received : {0}", info);

                    handler.Shutdown(SocketShutdown.Both);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }
Example #30
0
 private async System.Threading.Tasks.Task MakeDiscoverable()
 {
     // Make the system discoverable. Don'd repeatedly do this or the StartAdvertising will throw "cannot create a file when that file already exists"
     if (!App.IsBluetoothDiscoverable)
     {
         Guid BluetoothServiceUuid = new Guid("17890000-0068-0069-1532-1992D79BE4D8");
         try
         {
             provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(BluetoothServiceUuid));
             Windows.Networking.Sockets.StreamSocketListener listener = new Windows.Networking.Sockets.StreamSocketListener();
             listener.ConnectionReceived += OnConnectionReceived;
             await listener.BindServiceNameAsync(provider.ServiceId.AsString(), Windows.Networking.Sockets.SocketProtectionLevel.PlainSocket);
             //     SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
             // Don't bother setting SPD attributes
             provider.StartAdvertising(listener, true);
             App.IsBluetoothDiscoverable = true;
         }
         catch (Exception e)
         {
             string formatString = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothNoDeviceAvailableFormat");
             string confirmationMessage = string.Format(formatString, e.Message);
             DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage);
         }
     }
 }
 private void _listener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
 {
     ConnectionReceived?.Invoke(this, new RfcommConnectionReceivedEventArgs(new NetworkStream(args.Socket)));
 }