Exemple #1
0
        // Read out and print the message received from the socket.
        private async void StartReader(
            Windows.Networking.Sockets.StreamSocket socket,
            Windows.Storage.Streams.DataReader reader)
        {
            uint initialLength = 4;

            try
            {
                await reader.LoadAsync(initialLength);

                uint msgLength = (uint)reader.ReadInt32();

                try
                {
                    await reader.LoadAsync(msgLength);

                    string message = reader.ReadString(msgLength);
                    WriteMessageText("Received message: " + message + "\n");

                    // After receiving a message, listen for the next message.
                    StartReader(socket, reader);
                }
                catch (Exception e)
                {
                    WriteMessageText("Error: " + e.Message + "\n");
                    socket.Dispose();
                }
            }
            catch (Exception e)
            {
                WriteMessageText("Error: " + e.Message + "\n");
                socket.Dispose();
            }
        }
Exemple #2
0
 public void Disconnect()
 {
     // Monitor.Enter(nstreamlock);
     sock.Dispose();
     OnConnectionClosed();
     // Monitor.Exit(nstreamlock);
 }
Exemple #3
0
        private async Task OnSend()
        {
            if (string.IsNullOrEmpty(IPAddress))
            {
                await NotifyAsync("Destination IP is Empty");

                return;
            }
            IsBusy = true;
            var contentType = Enum.Parse <ContentType>(_selectedContentType.ToString());

            if (CoreApplication.Properties.ContainsKey("listener"))
            {
                Windows.Networking.Sockets.StreamSocket socket = null;
                try
                {
                    var host = new Windows.Networking.HostName(IPAddress);
                    socket = new Windows.Networking.Sockets.StreamSocket();
                    socket.Control.KeepAlive = false;
                    await socket.ConnectAsync(host, App.ServiceName);

                    switch (contentType)
                    {
                    case ContentType.File:
                        await SendFileAsync(socket.InputStream, socket.OutputStream);

                        break;

                    case ContentType.Code:
                        var language = Enum.Parse <HighlightedLanguage>(_language.ToString());
                        await SendContentAsync(socket.InputStream, socket.OutputStream, contentType, language);

                        break;

                    case ContentType.Text:
                        await SendContentAsync(socket.InputStream, socket.OutputStream, contentType);

                        break;
                    }
                }
                catch (Exception ex)
                {
                    await NotifyAsync(ex.Message);
                }
                finally
                {
                    socket?.Dispose();
                    IsBusy = false;
                }
            }
            else
            {
                await NotifyAsync("Somthing wrong.. Please Restart the app and try again");
            }
        }
Exemple #4
0
        public static async Task <XDocument> SockeRequest(
            string ip,
            string port,
            string strReq
            )
        {
            XDocument doc = null;

            try
            {
                var socket     = new Windows.Networking.Sockets.StreamSocket();
                var serverHost = new Windows.Networking.HostName(ip);
                await socket.ConnectAsync(serverHost, port);

                //Send request
                DataWriter writer = new DataWriter(socket.OutputStream);

                writer.WriteUInt32(writer.MeasureString(strReq));
                writer.WriteString(strReq);
                await writer.StoreAsync();

                await writer.FlushAsync();

                writer.DetachStream();
                writer.Dispose();


                //Read response
                Stream streamIn = socket.InputStream.AsStreamForRead();
                int    bsize    = 4096;
                byte[] buffer   = new byte[bsize];
                int    readByte = await streamIn.ReadAsync(
                    buffer,
                    0,
                    bsize
                    );

                if (readByte <= 0)
                {
                    //return null if there is no response
                    return(doc);
                }
                byte[] rdata = new byte[readByte];
                Array.Copy(buffer, rdata, readByte);
                streamIn.Dispose();
                socket.Dispose();


                doc = XDocument.Parse(Encoding.ASCII.GetString(rdata));
            }
            catch (Exception ex)
            {
            }
            return(doc);
        }
Exemple #5
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            if (this.btnConnect.Label == "Connect")
            {
                try
                {
                    Windows.Networking.HostName serverHost = new Windows.Networking.HostName(txtIP.Text);

                    string serverPort = txtPort.Text;
                    await socket.ConnectAsync(serverHost, serverPort);

                    Stream       streamOut = socket.OutputStream.AsStreamForWrite();
                    BinaryWriter writer    = new BinaryWriter(streamOut);
                    Stream       streamIn  = socket.InputStream.AsStreamForRead();
                    BinaryReader reader    = new BinaryReader(streamIn);

                    Boolean connOn     = true;
                    int     countLimit = handshake.Length + zonelabels.Length;

                    handshake[0] = App.createLoginString(this.txtPassword.Password);
                    int[] fixedLenght = new int[] { 53 };

                    this.txtEvent.Text  = "Connecting...";
                    this.txtStatus.Text = "Status: Connecting...";
                    await comms(reader, writer, handshake, answerLenghtArray, 0);

                    this.txtEvent.Text    = "Retrieving Zone Labels...";
                    this.txtStatus.Text   = "Status: Connected";
                    this.btnConnect.Label = "Disconnect";
                    await comms(reader, writer, zonelabels, fixedLenght, 2);

                    int i = 1;
                    foreach (CheckBox item in this.gridView.Items)
                    {
                        item.Content = Mappings.zoneLabel[i];
                        i++;
                    }


                    while (connOn)
                    {
                        await comms(reader, writer, retrieveInfo, fixedLenght, 1000);
                    }
                }
                catch (Exception er)
                {
                    Debug.WriteLine("ops...");
                    Debug.WriteLine(er.Message);
                }
            }
            else
            {
                socket.Dispose();
            }
        }
 public void StopExchange()
 {
     if (exchangeTask != null)
     {
         exchangeTask.Wait();
         socket.Dispose();
         writer.Dispose();
         socket       = null;
         exchangeTask = null;
         writer       = null;
     }
 }
Exemple #7
0
        public void Cleanup()
        {
            try
            {
                Writer.DetachStream();
                Reader.DetachStream();
                Writer.Dispose();
                Reader.Dispose();

                TvDirectSocket.Dispose();
                TvDirectSocket = null;
            }
            catch { }
        }
Exemple #8
0
        private void CloseSocket()
        {
            if (proximitySocket != null)
            {
                proximitySocket.Dispose();
                proximitySocket = null;
            }

            if (dataWriter != null)
            {
                dataWriter.Dispose();
                dataWriter = null;
            }
        }
Exemple #9
0
        private async void ReadThread(object host)
        {
            reading = true;
            Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket();

            await socket.ConnectAsync((Windows.Networking.HostName) host, InTheHand.Devices.Bluetooth.Rfcomm.RfcommServiceId.SerialPort.AsString());

            byte[] buffer = new byte[32];
            System.Text.StringBuilder sb = new StringBuilder();

            while (reading)
            {
                IBuffer returnedBuffer = await socket.InputStream.ReadAsync(buffer.AsBuffer(), (uint)buffer.Length, Windows.Storage.Streams.InputStreamOptions.Partial);

                // break loop if response is empty (connection fail etc)
                if (returnedBuffer.Length == 0)
                {
                    break;
                }

                string s = System.Text.Encoding.UTF8.GetString(buffer, 0, (int)returnedBuffer.Length);

                if (!string.IsNullOrEmpty(s))
                {
                    if (s.IndexOf('\0') > -1)
                    {
                        s = s.Substring(0, s.IndexOf('\0'));
                    }

                    sb.Append(s);

                    // Only process when we have a complete line
                    if (sb.ToString().EndsWith("\r"))
                    {
                        Dispatcher.BeginInvoke(new Action <string>(this.InsertMessage), sb.ToString());
                        sb.Clear();
                    }
                }
            }

            socket.Dispose();
        }
 public void Disconnect()
 {
     sock.Dispose();
     OnConnectionClosed();
 }
Exemple #11
0
        //netcode functions
        private async void StartClient(string data)
        {
            var hostName = new Windows.Networking.HostName("localhost"); // local machine

            //  IPAddress ipAddress = IPAddress.Parse("192.168.0.122"); //rpi

            // Create a TCP/IP socket.



            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // The name of the


                // Connect to the remote endpoint.
                using (var streamSocket = new Windows.Networking.Sockets.StreamSocket())
                {
                    if (lb1.Items.Count > 10)
                    {
                        lb1.Items.Clear();
                    }

                    lb1.Items.Add("connecting");
                    //new Windows.Networking.HostName("Legion-Surface")
                    //new Windows.Networking.HostName("raspberrypi")

                    await streamSocket.ConnectAsync(new Windows.Networking.HostName("192.168.0.122"), port.ToString());

                    // Send test data to the remote device.
                    if (lb1.Items.Count > 10)
                    {
                        lb1.Items.Clear();
                    }
                    lb1.Items.Add("connected. Sending Data");
                    string request = data + "<EOF>";
                    using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite())
                    {
                        using (var streamWriter = new StreamWriter(outputStream))
                        {
                            await streamWriter.WriteLineAsync(request);

                            await streamWriter.FlushAsync();
                        }
                    }


                    // Receive the response from the remote device.
                    // Receive(streamSocket);
                    //lb1.Items.Add("received the response: " + serverResponse);
                    streamSocket.Dispose();
                }
            }
            catch (Exception e)
            {
                Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(e.GetBaseException().HResult);
                this.lb1.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : e.Message);
            }
        }
Exemple #12
0
        public void Run()
        {
            try
            {
                socket = new Windows.Networking.Sockets.StreamSocket();
                UpgradeRequest request = null;
                try
                {
                    // connect to the eftlServer
                    if (String.Compare("ws", uri.Scheme, StringComparison.CurrentCultureIgnoreCase) == 0)
                    {
                        socket.ConnectAsync(remoteHostName, getPort().ToString(), Windows.Networking.Sockets.SocketProtectionLevel.PlainSocket).AsTask().Wait(5000);
                    }
                    else if (String.Compare("wss", uri.Scheme, StringComparison.CurrentCultureIgnoreCase) == 0)
                    {
                        socket.ConnectAsync(remoteHostName, getPort().ToString(), Windows.Networking.Sockets.SocketProtectionLevel.Ssl).AsTask().Wait(5000);
                    }

                    Windows.Networking.Sockets.SocketProtectionLevel l = socket.Information.ProtectionLevel;
                    Console.WriteLine("ProtectionLevel = " + l);

                    // send HTTP upgrade request
                    request = new UpgradeRequest(uri, protocols);
                    DataWriter writer = new DataWriter(socket.OutputStream);

                    String s = request.toString();
                    writer.WriteString(s);

                    // Call StoreAsync method to store the data to a backing stream
                    try
                    {
                        writer.StoreAsync().AsTask().Wait();
                        writer.FlushAsync().AsTask().Wait();
                    }
                    catch (Exception e) {
                        Console.WriteLine(e.StackTrace);
                    }
                    writer.DetachStream();
                }
                catch (Exception e)
                {
                    Exception exp = new Exception("failed to connect" + ((e.InnerException != null) ? e.InnerException.Message : ""));
                    notifyError(exp);
                }

                byte[]       buffer      = new byte[32768];
                IInputStream inputStream = socket.InputStream;

                try {
                    inputStream.ReadAsync(buffer.AsBuffer(), (uint)buffer.Length, InputStreamOptions.Partial).AsTask().Wait();
                    System.IO.Stream stream = new System.IO.MemoryStream(buffer);

                    // read HTTP upgrade response
                    UpgradeResponse response = UpgradeResponse.read(stream);
                    response.validate(request);

                    // get the agreed upon protocol
                    protocol = response.getProtocol();
                }
                catch (Exception e)
                {
                    notifyError(e);
                }

                // notify listener
                notifyOpen();

                // dispatch frames
                dispatch();
            }
            catch (Exception e)
            {
                notifyError(e);
            }
            finally
            {
                socket.Dispose();
            }
        }