Пример #1
0
 private void btnConnect_Click(object sender, EventArgs e)
 {
     btnConnect.Enabled = false;
     btnStop.Enabled    = true;
     clientName         = textName.Text;
     textStatus.Text   += "Connected" + System.Environment.NewLine;
     client.Connect(textHost.Text, Convert.ToInt32(textPort.Text));
     client.WriteLine("Connected");
     client.WriteLine("#N#A#M#E# " + clientName + ":");
 }
Пример #2
0
 private void ConnectButton_Click(object sender, EventArgs e)
 {
     client.Connect(serverAddressBox.Text, Convert.ToInt32(portBox.Text));
     conectingLabel.Show();
     //
     //send Player name and ready for connection status to server
     //
     //client.WriteLineAndGetReply(playerNameBox.Text, TimeSpan.FromSeconds(2));
     //client.WriteLineAndGetReply("Ready", TimeSpan.FromSeconds(2));
 }
Пример #3
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            btnConnect.Enabled = false;
            //Connect to server

            Client.Connect(txtHost.Text, Convert.ToInt32(txtPort.Text));
            Client.TcpClient.ReceiveBufferSize = 1;
            Client.TcpClient.SendBufferSize    = 1;
            //Client.TcpClient.NoDelay = true;
        }
Пример #4
0
 private void Connect()
 {
     while (Client.TcpClient == null || !Client.TcpClient.Connected)
     {
         try
         {
             Client.Connect(_ip, _port);
             return;
         }
         catch (Exception ex)
         {
             while (ex.InnerException != null)
             {
                 ex = ex.InnerException;
             }
             Console.WriteLine($"Error in reconnect: {ex.Message}\n{ex.StackTrace}\n");
         }
         Thread.Sleep(100);
     }
 }
Пример #5
0
        Message replyMsg;//= client.WriteLineAndGetReply("Hello world!", TimeSpan.FromSeconds(3));

        public void client1()
        {
            client.Connect("10.66.150.252", 8911);
            replyMsg = client.WriteLineAndGetReply("0,0,0,0,0,0,0,0", TimeSpan.FromSeconds(200));
            if (replyMsg != null)
            {
                Console.WriteLine(replyMsg.MessageString);
            }
            partija = replyMsg.MessageString.ToString();
            // return 1;
        }
Пример #6
0
        public static void SendScreenshotSignal(string hostName)
        {
            client = new SimpleTcpClient();
            client.StringEncoder = Encoding.UTF8;
            var host      = Dns.GetHostEntry("Papa-Romeo");
            var ipaddress = host.AddressList[6];

            client.Connect(ipaddress.ToString(), 51817);
            client.WriteLineAndGetReply("getScreenShot", TimeSpan.FromSeconds(10));
            client.DataReceived += client_DataReceived;
        }
Пример #7
0
 public void Connect(string ip, int port)
 {
     try
     {
         _client.Connect(ip, port);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Пример #8
0
 public TCPIPClient(string SerIP, int Port)
 {
     _Client = new SimpleTcpClient(SerIP, Port);
     _Client.Events.Connected    += Connected;
     _Client.Events.Disconnected += Disconnected;
     _Client.Events.DataReceived += DataReceived;
     //_Client.Keepalive.EnableTcpKeepAlives = true;
     //_Client.Settings.MutuallyAuthenticate = false;
     //_Client.Settings.AcceptInvalidCertificates = true;
     _Client.Logger = Logger;
     _Client.Connect();
 }
Пример #9
0
 public string Connect(string ip, int port)
 {
     try
     {
         client.Connect(ip, port);
         return("Success");
     }
     catch (Exception e)
     {
         return("Failed," + e.Message);
     }
 }
Пример #10
0
 private void Form1_Load(object sender, EventArgs e)
 {
     client = new SimpleTcpClient("127.0.0.1:9000");
     client.Events.Connected               += Events_Connected;
     client.Events.DataReceived            += Events_DataReceived;
     client.Events.Disconnected            += Events_Disconnected;
     axWindowsMediaPlayer1.PlayStateChange += new AxWMPLib._WMPOCXEvents_PlayStateChangeEventHandler(axWindowsMediaPlayer1_PlayStateChange);
     client.Connect();
     FormBorderStyle      = FormBorderStyle.None;
     WindowState          = FormWindowState.Maximized;
     pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
 }
Пример #11
0
        public FormMain()
        {
            InitializeComponent();
            //------------------------------------------------------------
            // Khởi tạo form hiển thị
            //------------------------------------------------------------
            formMainDisplay = new MainDisplay()
            {
                Dock = DockStyle.Fill, TopLevel = false, TopMost = true, Left = 50
            };
            pnlMainDisplay.Controls.Add(formMainDisplay);
            formMainDisplay.Show();
            //------------------------------------------------------------
            // Kết nối đến Server đọc code
            //------------------------------------------------------------
            try
            {
                ReaderTCPClient = new SimpleTcpClient();
                ReaderTCPClient.Connect("127.0.0.1", 12345);
                ReaderTCPClient.DataReceived += ProcessReaderServerMessage;
            }
            catch
            {
                MessageBox.Show("Không thể kết nối đến server đọc code");
                this.Dispose();
            }

            try
            {
                COMHandheld = new SerialPort("COM6", 9600, Parity.None, 8, StopBits.One);
                COMHandheld.DataReceived += ProcessHandheldPortMessage;
                COMHandheld.DtrEnable     = true;
                COMHandheld.Open();
            }
            catch
            {
                MessageBox.Show("Không thể kết nối tay cầm");
                this.Dispose();
            }

            try
            {
                COMGmes = new SerialPort("COM8", 9600, Parity.None, 8, StopBits.One);
                //COMGmes.DataReceived += ProcessHandheldPortMessage;
                COMGmes.DtrEnable = true;
                COMGmes.Open();
            }
            catch
            {
                MessageBox.Show("Không thể kết nối Gmes");
                this.Dispose();
            }
        }
Пример #12
0
 private void Connect_Click(object sender, EventArgs e)
 {
     Connect.Enabled = false;
     try
     {
         client.Connect(ipTB.Text, Convert.ToInt32(PortTB.Text));
     }
     catch (Exception ex)
     {
         ChatOutput.Text = Convert.ToString(ex);
     }
 }
Пример #13
0
        static void Main(string[] args)
        {
            SimpleTcpClient client = new SimpleTcpClient(); //Instantiate the client

            client.StringEncoder = Encoding.UTF8;           //Config
            client.DataReceived += Client_DataReceived;     //Subscribe to the DataRecieved event.
            client.Connect("127.0.0.1", 6500);              //Connect to the server
            while (true)                                    //Keep the console open until you close it.
            {
                //As long as the console is open, every message you type will be sent to the server.
                client.WriteLineAndGetReply(Console.ReadLine(), TimeSpan.FromSeconds(5));
            }
        }
Пример #14
0
 private void button2_Click(object sender, EventArgs e)
 {
     try
     {
         client.Connect();
         btnSend.Enabled    = true;
         btnConnect.Enabled = false;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Пример #15
0
 private void btncConnect_Click(object sender, EventArgs e)
 {
     try
     {
         client.Connect();
         btnSend.Enabled     = true;
         btncConnect.Enabled = false;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Error); // Exceção para mensagem de erro.
     }
 }
Пример #16
0
 public void connectToServer()
 {
     if (!client.IsConnected)
     {
         try
         {
             client.Connect();
         }
         catch (Exception ex)
         {
             client.Dispose();
         }
     }
 }
        /// <summary>
        /// On button Connect / Disconnect to the server
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_ConnectDisconnect_Click(object sender, EventArgs e)
        {
            string err;

            bool   bError = true;
            string s      = "Unknown error";

            if (!bConnected)
            {
                // try to connect
                if (client.Connect(textBox_ServerIP.Text, (int)numericUpDown_Port.Value, out err))
                {
                    s          = "Successfuly connected to the server";
                    bConnected = true;
                    bError     = false;
                }
                else
                {
                    s = "Failed to connect to server: " + err;
                }
            }
            else
            {
                // always disconnect on error (the client object will be disconnected anyways after calling Disconnect()
                bConnected = false;
                // try to disconnect
                if (client.Disconnect(out err))
                {
                    s      = "Successfuly disconnected from the server";
                    bError = false;
                }
                else
                {
                    s = "Failed to disconnect from server: " + err;
                }
            }

            if (bError)
            {
                MessageBox.Show(s, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            textBox_Receive.Text          += "DEBUG > " + s + "\r\n";
            textBox_Receive.SelectionStart = textBox_Receive.TextLength;
            textBox_Receive.ScrollToCaret();

            button_ConnectDisconnect.Text = bConnected ? "DISCONNECT" : "CONNECT";

            SetGUIstate(bConnected);
        }
Пример #18
0
 /// <inheritdoc cref="IServerConnection"/>
 public void Connect()
 {
     if (IsConnected)
     {
         return;
     }
     if (ConnectionSettings == null)
     {
         throw new InvalidOperationException("No settings found. Please set the connection settings first");
     }
     Client.AutoReconnect             = ConnectionSettings.AutoConnect;
     Client.CheckConnectivityInterval = ConnectionSettings.ReconnectInterval;
     Client.Connect(ConnectionSettings.Hostname, ConnectionSettings.Port);
 }
Пример #19
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if ((sender as Button).Content == "Odpojit")
            {
                (sender as Button).Content = "Připojit";
                OutputBox.Text            += "Odpojeno!\n";
                JmenoBox.IsReadOnly        = false;
                client.Write(JmenoBox.Text + " se odpojil.");
                client.Disconnect();
            }
            else
            {
                try
                {
                    client.Connect(IPBox.Text, int.Parse(PortBox.Text));
                    client.StringEncoder       = Encoding.UTF8;
                    (sender as Button).Content = "Odpojit";
                    OutputBox.Text            += "Připojeno!\n";
                    JmenoBox.IsReadOnly        = true;
                    client.Write(JmenoBox.Text + " se připojil.");
                }
                catch
                {
                    OutputBox.Text += "Nelze se připojit!\n";
                }
            }

            //if client.

            /*
             * OutputBox.Text = "";
             * OutputBox.IsReadOnly = true;
             *
             * string textToSend = "TestString";
             *
             * //---create a TCPClient object at the IP and port no.---
             * client = new TcpClient(IPBox.Text, int.Parse(PortBox.Text));
             * nwStream = client.GetStream();
             * OutputBox.Text += "Připojeno\n";
             *
             *
             * //---read back the text---
             * byte[] bytesToRead = new byte[client.ReceiveBufferSize];
             * int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
             * OutputBox.Text+=("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead) +"\n");
             * //Console.ReadLine();
             * client.Close();
             * OutputBox.Text += "Odpojeno\n";
             */
        }
Пример #20
0
        static void Main(string[] args)
        {
            var port      = Console.ReadLine();
            var ipConnect = Console.ReadLine();

            server = new SimpleTcpServer();
            server.ClientConnected += Server_ClientConnected;
            server.Start(int.Parse(port));
            Console.WriteLine("started");
            client = new SimpleTcpClient();
            client.Connect(ipConnect, 5820);
            Console.WriteLine("Connected");
            Console.ReadLine();
        }
Пример #21
0
 private void btConnect_Click(object sender, EventArgs e)
 {
     //conecta o cliente com o servidor
     try
     {
         client.Connect();
         btSend.Enabled    = true;
         btConnect.Enabled = false;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Пример #22
0
        public async Task <bool> TryConnect(NetworkAddress networkAddress)
        {
            bool didConnect = await Task.Run(() =>
            {
                try
                {
                    _tcpClient.Connect(networkAddress.IpAddress.ToString(), networkAddress.Port);
                    return(true);
                }
                catch (SocketException)
                {
                    return(false);
                }
            });

            if (didConnect)
            {
                // Measure latency
                Stopwatch stopwatch = Stopwatch.StartNew();

                Message reply = _tcpClient.WriteLineAndGetReply("#", TimeSpan.FromSeconds(5));

                stopwatch.Stop();

                if (reply.MessageString.StartsWith("#")) // Direct communication directive
                {
                    string replyNewlineTrimmed = reply.MessageString.TrimEnd('\r', '\n');

                    // Invisible UTF characters present at the front of the message (skip all non-digit characters
                    // to get offset ticks)
                    string replyFrontTrimmed = new string(replyNewlineTrimmed.SkipWhile(character => !char.IsDigit(character))
                                                          .ToArray());

                    long offsetTicks = long.Parse(replyFrontTrimmed);

                    // Halfway travel time calculation to sync TimeUtility accurately
                    TimeUtility.SyncWithOffset(TimeSpan.FromTicks(offsetTicks) + TimeSpan.FromTicks(stopwatch.ElapsedTicks / 2));

                    stopwatch.Stop();
                }
                else
                {
                    return(false);
                }

                _tcpClient.DelimiterDataReceived += (sender, e) => _clientReceiverService.Receive(e.MessageString);
            }

            return(didConnect);
        }
Пример #23
0
        private void connectButton_Click(object sender, EventArgs e)
        {
            if (connectButton.Text.Equals("Wyloguj"))
            {
                client.Disconnect();
                loginFormsVisible(true);
                this.Text = " ";
                return;
            }

            if (textBoxLogin.Text.Contains(":") || textBoxPassword.Text.Contains(":"))
            {
                MessageBox.Show("Login i hasło nie mogą zawierać znaku dwukropka  -> : <-", "Input Error");
                this.Text = " ";
                return;
            }

            if (textBoxLogin.Text.Equals("") || textBoxPassword.Text.Equals(""))
            {
                MessageBox.Show("Login i hasło nie mogą być puste");
                this.Text = " ";
                return;
            }

            if (textBoxLogin.Text.Contains(" ") || textBoxPassword.Text.Contains(" "))
            {
                MessageBox.Show("Login i hasło nie mogą zawierać znaku spacji");
                this.Text = " ";
                return;
            }

            client.Connect();
            client.Send($"{Messages.Client.Login}:{textBoxLogin.Text}:{textBoxPassword.Text}");
            this.Text = textBoxLogin.Text;
            loginFormsVisible(false);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            client2 = new SimpleTcpClient();
            client2.StringEncoder = Encoding.UTF8;
            client2.DataReceived += Client_DataReceived;
            client3 = new SimpleTcpClient();
            client3.StringEncoder = Encoding.UTF8;
            client3.DataReceived += Client_DataReceived;
            //String adip = "192.168.43.15";
            String adip   = "127.0.0.1";
            String adport = "8910";

            client2.Connect(adip, Convert.ToInt32(adport));
            client3.Connect(adip, Convert.ToInt32(adport));
        }
Пример #25
0
 private void btn_Connect_Click(object sender, EventArgs e)
 {
     player_name = "player2";
     if (ShowInputDialog(ref player_name, "Name", "Please input your name:") == DialogResult.OK)
     {
         string ip_address = string.Empty;
         if (ShowInputDialog(ref ip_address, "IP", "Please input an address:") == DialogResult.OK)
         {
             _isConnecting = true;
             _client       = new SimpleTcpClient();
             _client.Connect(ip_address, 6464);
             Console.WriteLine("Connecting...");
             _client.WriteLineAndGetReply("ask for connected", TimeSpan.FromSeconds(3));
             _client.Delimiter              = 0x13;
             _client.DelimiterDataReceived += (ssender, msg) =>
             {
                 if (msg.MessageString == "you are connected")
                 {
                     Console.WriteLine("Connected!");
                 }
                 else
                 {
                     string[] buffer = msg.MessageString.Split(',');
                     Chess    chess  = _game.PlaceAChess(Int32.Parse(buffer[1]), Int32.Parse(buffer[2]));
                     if (chess != null)
                     {
                         chess.Name = "chess";
                         this.Invoke((MethodInvoker)(() => this.Controls.Add(chess)));
                         this.Invoke((MethodInvoker)(() => this.Refresh()));
                         _audio.Play();
                     }
                     if (_game.IsGameOver)
                     {
                         if (!_game.IsBlack)
                         {
                             this.Invoke((MethodInvoker)(() => MessageBox.Show("Black wins")));
                         }
                         else
                         {
                             this.Invoke((MethodInvoker)(() => MessageBox.Show("White wins")));
                         }
                         this.Invoke((MethodInvoker)(() => Reset()));
                     }
                 }
             };
         }
     }
 }
Пример #26
0
        public static void initiateClient(String IP)
        {
            client = new SimpleTcpClient(IP + ":37664");
            //int returnType = 0;
            // set events
            client.Events.Connected    += Connected;
            client.Events.Disconnected += Disconnected;
            client.Events.DataReceived += DataReceivedClient;

            client.Connect();

            Application.Current.Dispatcher.Invoke((Action) delegate {
                window1 = new connectPremission();
                window1.Show();
            });
        }
Пример #27
0
 private void btnConnect_Click(object sender, EventArgs e)
 {
     btnConnect.Enabled = false;
     try
     {
         label6.Text      = "connected to host";
         label6.ForeColor = System.Drawing.Color.Green;
         Client.Connect(txtHost.Text, Convert.ToInt32(txtPort.Text));
     }
     catch (Exception)
     {
         label6.Text      = "ERROR: could not connect to host";
         label6.ForeColor = System.Drawing.Color.Red;
         //throw;
     }
 }
Пример #28
0
        private void Form1_Load(object sender, EventArgs e)
        {
            engraver.Connect(ip, port);
            engraver.StringEncoder = Encoding.ASCII;
            engraver.DataReceived += Engraver_DataReceived;

            numLOC8.Value = 1;

            //SetProgram(PRGM);
            bwGetSettings.RunWorkerAsync();
            bwReadyStateCheck.RunWorkerAsync();

            //Thread.Sleep(100);
            //timerGetSettings.Enabled = true;
            //Thread.Sleep(300);
            //timerReady.Enabled = true;
        }
Пример #29
0
 private void btnCheckServerConnect_Click(object sender, EventArgs e)
 {
     try
     {
         using (var client = new SimpleTcpClient())
         {
             client.Connect(txtIpServer.Text.Trim(), Convert.ToInt32(txtPortServer.Text.Trim()));
             MetroMessageBox.Show(this, "Connect successful", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
             serverPort = Convert.ToInt32(txtPortServer.Text.Trim());
             serverIP   = txtIpServer.Text.Trim();
         }
     }
     catch (Exception)
     {
         MetroMessageBox.Show(this, "Connect fail", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Пример #30
0
        public TCPClient()
        {
            client = new SimpleTcpClient();
            client.StringEncoder = Encoding.UTF8;
            client.DataReceived += Client_DataRecieved;

            // try to connect to server
            try
            {
                client.Connect(Client.Properties.Settings.SERVERIPADDRESS, Client.Properties.Settings.SERVERPORT);
                Log.LogFile.INSTANCE.WriteLine(Client.Properties.Settings.SERVERIPADDRESS + ":" + Client.Properties.Settings.SERVERPORT);
                Log.LogFile.INSTANCE.WriteLine(client.TcpClient.Connected.ToString());
            }
            catch (System.Net.Sockets.SocketException)
            {
                Log.LogFile.INSTANCE.WriteLine("Not possible connect to " + Client.Properties.Settings.SERVERIPADDRESS + ":" + Client.Properties.Settings.SERVERPORT);
            }
        }