async void SendKeepAlive(Object stateInfo)
        {
            if (bindedDevice != null && bindedDevice.BindActive == false)
            {
                bindedDevice = null;
                await tcpClient.DisconnectAsync();

                return;
            }
            else if (keepAliveWatch.ElapsedMilliseconds > 4 * keepAliveTimer)
            {
                if (bindedDevice != null)
                {
                    bindedDevice.BindActive = false;
                }
                await tcpClient.DisconnectAsync();

                isTcpThreadActive = false;
                BindDropped();
                return;
            }
            byte[] msg = Encoding.UTF8.GetBytes("a*\r");
            tcpClient.WriteStream.Write(msg, 0, msg.Length);
            await tcpClient.WriteStream.FlushAsync();
        }
        public async Task DisconnectAsync()
        {
            _shouldBeConnected = false;
            await _client.DisconnectAsync();

            _client = null;
        }
Exemple #3
0
 public void send_text(string src, out int length)
 {
     client.ConnectAsync(address_con_to, port[0]);
     byte[] bytes = (new System.Text.UTF8Encoding()).GetBytes(src);
     length = bytes.Length;
     foreach (byte a in bytes)
     {
         client.WriteStream.WriteByte(a);
         client.WriteStream.FlushAsync();
         Task.Delay(50);
     }
     client.DisconnectAsync();
 }
Exemple #4
0
        private void Init()
        {
            try
            {
                mSocket.ConnectAsync(SERVER_ADDRESS, SERVER_PORT);
            }
            catch (Exception ex)
            {
                mSocket.DisconnectAsync();
            }

            // we're connected!
        }
Exemple #5
0
 /// <summary>
 /// Disconnects us from the IGS server and closes all IGS games.
 /// </summary>
 /// <returns></returns>
 public async Task DisconnectAsync()
 {
     try
     {
         await _client.DisconnectAsync();
     }
     catch
     {
         // Ignore all TCP errors.
     }
     finally
     {
         ConnectionLost();
     }
 }
Exemple #6
0
        async void SocketButton_Clicked(object sender, EventArgs e)
        {
            var address    = "10.0.2.2";
            var port       = 2001;
            var sendString = $"{Name.Text}," +
                             $"{Product.Text}," +
                             $"{Lot.Text}," +
                             $"{Date.Date.ToString("yyyy/MM/dd")} {Time.Time}\n";

            using (var client = new TcpSocketClient())
            {
                try
                {
                    await client.ConnectAsync(address, port);

                    var enc       = Encoding.UTF8;
                    var sendBytes = enc.GetBytes(sendString);
                    foreach (var byteData in sendBytes)
                    {
                        client.WriteStream.WriteByte(byteData);
                        await client.WriteStream.FlushAsync();
                    }

                    await client.DisconnectAsync();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.InnerException);
                }
            }
        }
        public async Task Send(string ip, int port)
        {
            var r = new Random();

            RaiseInfoEvent(string.Format("Connecting to: {0}:{1}", ip, port));
            _outChannel = new TcpSocketClient();
            RaiseOutChannelStarted(true);

            await _outChannel.ConnectAsync(ip, port);

            RaiseInfoEvent("We're connected!");

            for (int i = 0; i < 5; i++)
            {
                // write to the 'WriteStream' property of the socket client to send data
                var nextByte = (byte)r.Next(0, 254);
                RaiseInfoEvent(string.Format("Sending: {0}", nextByte));
                _outChannel.WriteStream.WriteByte(nextByte);
                await _outChannel.WriteStream.FlushAsync();

                // wait a little before sending the next bit of data
                await Task.Delay(TimeSpan.FromMilliseconds(500));
            }

            await _outChannel.DisconnectAsync();

            RaiseInfoEvent("Message sent!");
            RaiseOutChannelStarted(false);
            IsSending = false;
        }
Exemple #8
0
        private async void TcpServer()
        {
            // Send Message Via TCP
            var address = "255.255.255.255";
            var port    = 25000;
            var r       = new Random();
            var client  = new TcpSocketClient();
            await client.ConnectAsync(address, port);

            Debug.WriteLine("we're connected!");
            var msg = $"DeviceState: {_product.State} DeviceLevel: {_product.level}";

            byte[] toBytes = Encoding.ASCII.GetBytes(msg);
            // we're connected!
            try
            {
                for (int i = 0; i < toBytes.Length; i++)
                {
                    // write to the 'WriteStream' property of the socket client to send data

                    client.WriteStream.WriteByte(toBytes[i]);
                    await client.WriteStream.FlushAsync();

                    // wait a little before sending the next bit of data
                    //await Task.Delay(TimeSpan.FromMilliseconds(500));
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }


            await client.DisconnectAsync();
        }
        public async void closeConnection()
        {
            //if (isConnected())
            //{
            await socket.DisconnectAsync();

            //}
        }
 public async Task Disconnect()
 {
     if (_client != null)
     {
         await _client.DisconnectAsync();
     }
     _client = null;
 }
Exemple #11
0
 public void Close()
 {
     if (_client != null)
     {
         _client.DisconnectAsync().Wait();
     }
     _client    = null;
     _connected = false;
 }
Exemple #12
0
        private async void OnDisConnectClicked(object sender, EventArgs e)
        {
            //var bytes = Encoding.UTF8.GetBytes("$");
            //await client.WriteStream.WriteAsync(bytes, 0, bytes.Length);
            //await client.WriteStream.FlushAsync();
            await client.WriteStringAsync("Disconnect", "$"); //$ 結束符號

            await client.DisconnectAsync();
        }
Exemple #13
0
        public async Task DisconnectAsync()
        {
            IsConnected = false;

            _receivedMessages.Unmerge(this);
            _jsonProtocolMessenger.StopExecuting();
            await _tcpSocketClient.DisconnectAsync();

            _tcpSocketClient = new TcpSocketClient();
        }
 /// <summary>
 /// Releases unmanaged and - optionally - managed resources.
 /// </summary>
 /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 protected override async void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (_client != null)
         {
             //_client.Dispose();
             await _client.DisconnectAsync();
         }
     }
     base.Dispose(disposing);
 }
Exemple #15
0
        public async void CreateTCPClient()
        {
            try
            {
                App.DevPage.devPageActIndicator(true);
                client = new TcpSocketClient();
                await client.ConnectAsync(address, port);

                TCPConnected();

                string finalData = "";

                await Task.Run(() =>
                {
                    try
                    {
                        byte[] byteData = new byte[1];
                        while (client.ReadStream.Read(byteData, 0, 1) != 0)
                        {
                            if (byteData[0] == 0x02)
                            {
                                finalData = "";
                            }
                            else if (byteData[0] == 0x04)
                            {
                                HandelReceivedData(finalData);
                                finalData = "";
                            }
                            else
                            {
                                finalData += Convert.ToChar(byteData[0]);
                            }
                        }
                        TCPDisconnected();
                    }
                    catch (Exception)
                    {
                        TCPDisconnected();
                    }
                });

                await client.DisconnectAsync();
            }
            catch (Exception e)
            {
                client = null;
                Debug.WriteLine(e.ToString());
                TCPDisconnected();
            }
        }
        /// <summary>
        /// Disconnect the current device an dispose all ressources
        /// </summary>
        public static async void Disconnect()
        {
            connected = false;
            try
            {
                await tcpSocketClient.DisconnectAsync();

                tcpSocketClient.Dispose();
            }
            catch (Exception e)
            {
                throw new Exception(305, "The device could not disconnect");
            }
        }
Exemple #17
0
        private void InitView()
        {
            Content = new StackLayout()
            {
                Padding  = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0),
                Children =
                {
                    new ClientConnectView("127.0.0.1",                  11000, this)
                    {
                        ConnectTapped = async(s,                        i) =>
                        {
                            await _client.ConnectAsync(s,               i);
                            _canceller = new CancellationTokenSource();

                            Task.Factory.StartNew(() =>
                            {
                                foreach (var msg in _client.ReadStrings(_canceller.Token))
                                {
                                    _messagesSub.OnNext(msg);
                                }
                            },                                          TaskCreationOptions.LongRunning);

                            return(true);
                        },
                        DisconnectTapped = async() =>
                        {
                            var bytes = Encoding.UTF8.GetBytes("<EOF>");
                            await _client.WriteStream.WriteAsync(bytes,     0, bytes.Length);
                            await _client.WriteStream.FlushAsync();

                            _canceller.Cancel();
                            await _client.DisconnectAsync();
                        }
                    },
                    new MessagesView(_messagesObs,                      true)
                    {
                        SendData = async s =>
                        {
                            await _client.WriteStringAsync(s);

                            return(new Message
                            {
                                Text = s,
                                DetailText = String.Format("Sent at {0}",DateTime.Now.ToString("HH:mm:ss"))
                            });
                        }
                    }
                }
            };
        }
Exemple #18
0
        protected override async void OnAppearing()
        {
            base.OnAppearing();
            client = new TcpSocketClient();
            try
            {
                await client.ConnectAsync("ws://192.168.1.69:81", "tcp");

                client.WriteStream.WriteByte(Convert.ToByte("ledon"));
                await client.WriteStream.FlushAsync();

                await client.DisconnectAsync();
            }
            catch { }
        }
Exemple #19
0
 public async void TCPDisconnected()
 {
     try
     {
         if (client != null)
         {
             await client.DisconnectAsync();
         }
         Device.BeginInvokeOnMainThread(() =>
         {
             App.DevPage.normalSLayout.IsVisible  = false;
             App.DevPage.connectSLayout.IsVisible = true;
         });
         App.streamSendNext = true;
     }
     catch (Exception)
     {
         throw;
     }
 }
Exemple #20
0
        public async Task Connect()
        {
            var address = "172.24.1.1";
            var port    = 5050;
            var r       = new Random();
            var client  = new TcpSocketClient();
            await client.ConnectAsync(address, port);

            // we're connected!
            for (int i = 0; i < 5; i++)
            {
                // write to the 'WriteStream' property of the socket client to send data
                var nextByte = (byte)r.Next(0, 254);
                client.WriteStream.WriteByte(nextByte);
                await client.WriteStream.FlushAsync();

                // wait a little before sending the next bit of data
                await Task.Delay(TimeSpan.FromMilliseconds(500));
            }
            await client.DisconnectAsync();
        }
        public async Task SendData(string address, int port, string message)
        {
            Console.WriteLine("Sending " + message + " to " + address + " at " + port);


            var client = new TcpSocketClient();
            await client.ConnectAsync(address, port);

            byte[] data = Encoding.ASCII.GetBytes(message);

            client.WriteStream.Write(data, 0, data.Length);


            await client.WriteStream.FlushAsync();

            // wait a little before sending the next bit of data
            await Task.Delay(TimeSpan.FromMilliseconds(500));


            await client.DisconnectAsync();
        }
 public async Task Disconnect()
 {
     await client.DisconnectAsync();
 }
 public void CloseConnection()
 {
     tcpClient.DisconnectAsync().Wait();
     connected = false;
 }
        public async void doSend(Packet sendpacket)
        {
            Debug.WriteLine($"PP:doSend {sendpacket.method} {sendpacket.toip} {sendpacket.toport} {sendpacket.ascii}");
//            byte[] bytesToSend = System.Text.Encoding.UTF8.GetBytes(sendpacket.ascii);
            byte[] bytesToSend = sendpacket.getByteArray();

            try
            {
                sendpacket.error = "";
                await tcp.DisconnectAsync();

                if (sendpacket.isTCP())
                {
                    await tcp.ConnectAsync(sendpacket.toip, sendpacket.toport);

                    await tcp.WriteStream.WriteAsync(bytesToSend, 0, bytesToSend.Length);

                    await tcp.DisconnectAsync();

                    /*
                     * // wait a little before reading
                     * var bytesRecv = new byte[20];
                     * //tcp.ReadStream.ReadTimeout = 200;
                     * //not async, so it can time out.
                     * await Task.Delay(TimeSpan.FromMilliseconds(00));
                     * if (tcp.ReadStream.Length > 0)
                     * {
                     *  int bytesRead = await tcp.ReadStream.ReadAsync(bytesRecv, 0, 20);
                     *  if (bytesRead > 0)
                     *  {
                     *      Packet receivepkt = new Packet();
                     *      receivepkt.toip = sendpacket.fromip;
                     *      receivepkt.fromip = sendpacket.toip;
                     *      receivepkt.fromport = sendpacket.toport;
                     *      Array.Resize(ref bytesRecv, bytesRead);
                     *      receivepkt.hex = Packet.byteArrayToHex(bytesRecv);
                     *      MessagingCenter.Send(this, Events.NEW_TRAFFIC_PACKET, receivepkt);
                     *  }
                     *
                     * }
                     */
                }
                if (sendpacket.isUDP())
                {
                    await udpServer.SendToAsync(bytesToSend, sendpacket.toip, sendpacket.toport);
                }
            }
            catch (Exception eSend)
            {
                sendpacket.error = "Error: " + eSend.Message;
                Debug.WriteLine("PP:Exception : " + eSend.Message);
            }


            Debug.WriteLine("PP:Before Message");
            MessagingCenter.Send(this, Events.NEW_TRAFFIC_PACKET, sendpacket);
            Debug.WriteLine("PP:After Message");



            Debug.WriteLine("PP:Finished");
        }
Exemple #25
0
        public async Task Disconnect()
        {
            await _client.DisconnectAsync();

            _client = null;
        }
Exemple #26
0
 public Task DisconnectAsync()
 {
     return(_client.DisconnectAsync());
 }
        public async Task StopAsync()
        {
            await client.DisconnectAsync();

            client.Dispose();
        }
Exemple #28
0
 private void Button_Click_2(object sender, RoutedEventArgs e)
 {
     client.DisconnectAsync();
 }
Exemple #29
0
 private void Disconnect()
 {
     _client.DisconnectAsync();
     _isConnected = false;
     OnServerDisconnected?.Invoke(this, new EventArgs());
 }
        public async void receiveTCP()
        {
            try
            {
                bool   validMsg    = false;
                bool   msgComplete = false;
                byte[] finalMsg    = new byte[1000];


                int index_finalMsg = 0;

                await Task.Run(async() =>
                {
                    try
                    {
                        byte[] byteTCP = new byte[1];
                        while (client.ReadStream.Read(byteTCP, 0, 1) != 0)
                        {
                            /*determine if the message is valid before doing anything else*/
                            if (byteTCP[0] == 0x02)
                            {
                                validMsg = true;
                            }
                            else if (byteTCP[0] == 0x04)
                            {
                                msgComplete = true;
                            }
                            /*determine if the message is valid before doing anything else*/

                            /*save the message if it is valid*/
                            if (validMsg == true)
                            {
                                finalMsg[index_finalMsg] = byteTCP[0];
                                index_finalMsg++;
                            }
                            if (msgComplete == true)
                            {
                                validMsg = false;
                                /*Handle the complete message*/
                                await handleTCPAsync(finalMsg);
                                /*Handle the complete message*/
                                msgComplete    = false;
                                index_finalMsg = 0;
                                finalMsg       = new byte[1000];
                            }
                            /*save the message if it is valid*/
                        }
                        await client.DisconnectAsync();
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            App.myMainPage.tcpDisconnectedView();
                        });
                    }
                    catch (Exception e)
                    {
                        await client.DisconnectAsync();
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            App.myMainPage.tcpDisconnectedView();
                        });
                    }
                });
            }
            catch (Exception e)
            {
                await client.DisconnectAsync();

                Device.BeginInvokeOnMainThread(() =>
                {
                    App.myMainPage.tcpDisconnectedView();
                });
            }
        }