示例#1
0
        private static void InitializeClient()
        {
            if (!useSsl)
            {
                client = new WatsonTcpClient(serverIp, serverPort);
            }
            else
            {
                certFile             = InputString("Certificate file:", "test.pfx", false);
                certPass             = InputString("Certificate password:"******"password", false);
                acceptInvalidCerts   = InputBoolean("Accept Invalid Certs:", true);
                mutualAuthentication = InputBoolean("Mutually authenticate:", true);

                client = new WatsonTcpClient(serverIp, serverPort, certFile, certPass);
                client.AcceptInvalidCertificates = acceptInvalidCerts;
                client.MutuallyAuthenticate      = mutualAuthentication;
            }

            client.AuthenticationFailure   += AuthenticationFailure;
            client.AuthenticationRequested  = AuthenticationRequested;
            client.AuthenticationSucceeded += AuthenticationSucceeded;
            client.ServerConnected         += ServerConnected;
            client.ServerDisconnected      += ServerDisconnected;
            client.StreamReceived          += StreamReceived;
            client.Logger = Logger;
            // client.Debug = true;
            client.Start();
        }
示例#2
0
        private static void ConnectClient()
        {
            if (client != null)
            {
                client.Dispose();
            }

            if (!useSsl)
            {
                client = new WatsonTcpClient(serverIp, serverPort);
            }
            else
            {
                client = new WatsonTcpClient(serverIp, serverPort, certFile, certPass);
                client.AcceptInvalidCertificates = acceptInvalidCerts;
                client.MutuallyAuthenticate      = mutualAuthentication;
            }

            client.AuthenticationFailure   = AuthenticationFailure;
            client.AuthenticationRequested = AuthenticationRequested;
            client.AuthenticationSucceeded = AuthenticationSucceeded;
            client.ServerConnected         = ServerConnected;
            client.ServerDisconnected      = ServerDisconnected;
            client.MessageReceived         = MessageReceived;
            client.ReadDataStream          = true;
            client.ReadStreamBufferSize    = 65536;
            client.Debug = debug;
            client.Start();
        }
示例#3
0
        private static void Main(string[] args)
        {
            rng  = new Random((int)DateTime.Now.Ticks);
            data = InitByteArray(262144, 0x00);
            Console.WriteLine("Data MD5: " + BytesToHex(Md5(data)));
            Console.WriteLine("Starting in 3 seconds...");

            server = new WatsonTcpServer(null, serverPort);
            server.ClientConnected    += ServerClientConnected;
            server.ClientDisconnected += ServerClientDisconnected;
            server.MessageReceived    += ServerMsgReceived;
            server.Start();

            Thread.Sleep(3000);

            c = new WatsonTcpClient("localhost", serverPort);
            c.ServerConnected    += ClientServerConnected;
            c.ServerDisconnected += ClientServerDisconnected;
            c.MessageReceived    += ClientMsgReceived;
            c.Start();

            Console.WriteLine("Press ENTER to exit");

            for (int i = 0; i < clientThreads; i++)
            {
                Task.Run(() => ClientTask());
            }

            Console.ReadLine();
        }
示例#4
0
        public void ConnectToServer()
        {
            tcpClient = new WatsonTcpClient(serverip, 8901);
            tcpClient.MessageReceived    += MessageReceived;
            tcpClient.ServerDisconnected += _ServerDisconnected;

            try
            {
                Console.Out.WriteLine("[Client] Trying to connect to server with ip: " + serverip);
                tcpClient.Start();
            }
            catch (SocketException e)
            {
                Console.Out.WriteLine(e);
            }

            if (tcpClient.Connected)
            {
                Console.Out.WriteLine("[Client] Connection sucessful");
                ServerConnected(this, new EventArgs());
                StopUDP();
            }
            else
            {
                Console.Out.WriteLine("[Client] Connection failed");
            }
        }
示例#5
0
        static void InitializeClient()
        {
            if (!useSsl)
            {
                client = new WatsonTcpClient(serverIp, serverPort);
            }
            else
            {
                certFile             = Common.InputString("Certificate file:", "test.pfx", false);
                certPass             = Common.InputString("Certificate password:"******"password", false);
                acceptInvalidCerts   = Common.InputBoolean("Accept Invalid Certs:", true);
                mutualAuthentication = Common.InputBoolean("Mutually authenticate:", true);

                client = new WatsonTcpClient(serverIp, serverPort, certFile, certPass);
                client.AcceptInvalidCertificates = acceptInvalidCerts;
                client.MutuallyAuthenticate      = mutualAuthentication;
            }

            client.AuthenticationFailure   = AuthenticationFailure;
            client.AuthenticationRequested = AuthenticationRequested;
            client.AuthenticationSucceeded = AuthenticationSucceeded;
            client.ServerConnected         = ServerConnected;
            client.ServerDisconnected      = ServerDisconnected;
            client.MessageReceived         = MessageReceived;
            client.ReadDataStream          = true;
            client.ReadStreamBufferSize    = 65536;
            // client.Debug = true;
            client.Start();
        }
示例#6
0
        private static void InitSocketClient()
        {
            WatsonTcpClient client = new WatsonTcpClient(SERVER, Port)
            {
                ServerConnected    = ServerConnected,
                ServerDisconnected = ServerDisconnected,
                MessageReceived    = MessageReceived,
                Debug = false
            };

            client.Start();

            bool runForever = true;

            do
            {
                if (ObjectQueue.Count > 0 && ObjectQueue.TryDequeue(out var @object))
                {
                    if (@object is ColoredMessage)
                    {
                        var coloredMsg = @object as ColoredMessage;
                        client.Send(coloredMsg.Message, coloredMsg.Color);
                    }
                }

                Thread.Sleep(100);
            }while (runForever);
        }
示例#7
0
        private void Test2ClientWorker()
        {
            try
            {
                using (WatsonTcpClient client = new WatsonTcpClient("127.0.0.1", 10000))
                {
                    client.MessageReceived += Test2ClientMsgRcv;
                    client.Start();

                    for (int i = 0; i < _NumMessages; i++)
                    {
                        if (client.Send(_MsgBytes))
                        {
                            _MessagesSentSuccess++;
                            _MessagesProcessing++;
                            _BytesSent += _MsgBytes.Length;
                        }
                        else
                        {
                            _MessagesSentFailed++;
                        }
                    }
                }

                _RunningTasks--;
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.ToString());
            }
        }
示例#8
0
        static void Main(string[] args)
        {
            Task.Run(() =>
            {
                WatsonTcpClient client = new WatsonTcpClient("10.1.2.3", 1234); // NonExistant Server

                client.ServerConnected    += HandleServerConnected;
                client.ServerDisconnected += HandleServerDisconnected;
                client.MessageReceived    += HandleMessageReceived;

                try
                {
                    Console.WriteLine("Starting Client");
                    client.Start();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: {0}", ex.Message);
                    client.Dispose();
                }
            });

            Console.WriteLine("Waiting on NullReferenceException");
            Thread.Sleep(10000);
        }
示例#9
0
        internal void Start()
        {
            string ip   = null;
            int    port = -1;

            Common.ParseIpPort(PeerNode.IpPort, out ip, out port);

            if (PeerNode.Ssl)
            {
                _TcpClient = new WatsonTcpClient(
                    ip,
                    port,
                    PeerNode.PfxCertificateFile,
                    PeerNode.PfxCertificatePassword);

                Logger?.Invoke("[MeshClient] Starting TCP client with SSL to connect to " + ip + ":" + port);
            }
            else
            {
                _TcpClient = new WatsonTcpClient(
                    ip,
                    port);

                Logger?.Invoke("[MeshClient] Starting TCP client to connect to " + ip + ":" + port);
            }

            _TcpClient.AcceptInvalidCertificates = _Settings.AcceptInvalidCertificates;
            _TcpClient.MutuallyAuthenticate      = _Settings.MutuallyAuthenticate;
            _TcpClient.StreamBufferSize          = _Settings.StreamBufferSize;

            _TcpClient.AuthenticationRequested  = MeshClientAuthenticationRequested;
            _TcpClient.AuthenticationSucceeded += MeshClientAuthenticationSucceeded;
            _TcpClient.AuthenticationFailure   += MeshClientAuthenticationFailure;
            _TcpClient.ServerConnected         += MeshClientServerConnected;
            _TcpClient.ServerDisconnected      += MeshClientServerDisconnected;
            _TcpClient.StreamReceived          += MeshClientStreamReceived;

            try
            {
                _TcpClient.Start();
            }
            catch (SocketException)
            {
                Task unawaited = Task.Run(() => ReconnectToServer());
                ServerDisconnected?.Invoke(this, new ServerConnectionEventArgs(PeerNode));
            }
            catch (Exception e)
            {
                Logger?.Invoke("[MeshClient] Client exception: " + Environment.NewLine + Common.SerializeJson(e, true));
                Task unawaited = Task.Run(() => ReconnectToServer());
                ServerDisconnected?.Invoke(this, new ServerConnectionEventArgs(PeerNode));
            }

            Logger?.Invoke("[MeshClient] Client started");
        }
示例#10
0
 public void ClientStart()
 {
     try
     {
         client.Start();
     }
     catch (SocketException)
     {
         MessageBox.Show("Servis Cevap Vermiyor. Program Kapatılacak");
         Application.Exit();
     }
 }
示例#11
0
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.SelectedItem = "Online";
            userLabel.Text         = usernameShorten(userName);
            if (!string.IsNullOrEmpty(picAddress))
            {
                userAvatar.Image = Bitmap.FromFile(picAddress);
            }

            userColorSys = Color.FromName(userColor);

            userAvatar.MouseHover += userAvatar_MouseHover;
            userLabel.MouseHover  += userAvatar_MouseHover;

            bool isConnected = false;

            while (!isConnected && !demoMode)
            {
                try
                {
                    client.Start();
                    isConnected = true;
                }
                catch (Exception)
                {
                    DialogResult result = MessageBox.Show("A connection to Xalarwse servers could not be established." +
                                                          "\nSelect \"Retry\" to reattempt a connection to Xalarwse servers." +
                                                          "\nSelect \"Cancel\" to cancel reconnection and launch the program in offline (demo) mode.  " +
                                                          "\nYou can always restard the program later from offline (demo) mode.",
                                                          "Not Connected", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
                    if (result == DialogResult.Cancel)
                    {
                        demoMode  = true;
                        this.Text = windowName + " (offline mode)";
                        //reconnectGroupBox.Visible = true; DISABLED
                    }
                }
            }
        }
示例#12
0
        internal void RunTest()
        {
            using (WatsonTcpServer server = new WatsonTcpServer("127.0.0.1", 10000))
            {
                server.MessageReceived = Test1ServerMsgRcv;
                server.Start();

                using (WatsonTcpClient client = new WatsonTcpClient("127.0.0.1", 10000))
                {
                    client.MessageReceived = Test1ClientMsgRcv;
                    client.Start();

                    _Stopwatch.Start();

                    for (int i = 0; i < _NumMessages; i++)
                    {
                        if (client.Send(_MsgBytes))
                        {
                            _MessageSuccess++;
                            _BytesSent += _MessageSize;
                        }
                        else
                        {
                            _MessageFailed++;
                        }
                    }

                    _Stopwatch.Stop();
                }
            }

            Console.WriteLine("");
            Console.WriteLine("Results:");
            Console.WriteLine("  Messages sent successfully  : " + _MessageSuccess);
            Console.WriteLine("  Messages failed             : " + _MessageFailed);
            Console.WriteLine("  Bytes sent successfully     : " + _BytesSent);
            Console.WriteLine("  Bytes received successfully : " + _BytesReceived);

            decimal secondsTotal   = _Stopwatch.ElapsedMilliseconds / 1000;
            decimal bytesPerSecond = _BytesSent / secondsTotal;
            decimal kbPerSecond    = bytesPerSecond / 1024;
            decimal mbPerSecond    = kbPerSecond / 1024;

            Console.WriteLine("  Elapsed time (ms)           : " + _Stopwatch.ElapsedMilliseconds + "ms");
            Console.WriteLine("  Elapsed time (seconds)      : " + decimal.Round(secondsTotal, 2) + "s");
            Console.WriteLine("  Bytes per second            : " + decimal.Round(bytesPerSecond, 2) + "B/s");
            Console.WriteLine("  Kilobytes per second        : " + decimal.Round(kbPerSecond, 2) + "kB/s");
            Console.WriteLine("  Megabytes per second        : " + decimal.Round(mbPerSecond, 2) + "MB/s");
            Console.WriteLine("");
        }
示例#13
0
 static void Main(string[] args)
 {
     try
     {
         _Client = new WatsonTcpClient("127.0.0.1", 9000);
         _Client.Events.MessageReceived += MessageReceived;
         _Client.Start();
         _Client.Send("Hello!");
         _Client.Dispose();
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
     }
 }
示例#14
0
        static void Main(string[] args)
        {
            try
            {
                var watsonServer = new WatsonTcpServer("127.0.0.1", Port)
                {
                    Compression   = CompType,
                    Logger        = Console.WriteLine,
                    DebugMessages = true
                };

                watsonServer.MessageReceived += (sender, message) =>
                {
                    Console.WriteLine("Server received message: " + Encoding.UTF8.GetString(message.Data));
                    watsonServer.Send(message.IpPort, message.Data);
                };

                watsonServer.Start();
                Task.Delay(1000).Wait();

                var client = new WatsonTcpClient("127.0.0.1", Port)
                {
                    Compression   = CompType,
                    Logger        = Console.WriteLine,
                    DebugMessages = true
                };

                client.MessageReceived += (sender, message) =>
                {
                    Console.WriteLine("Client received message: " + Encoding.UTF8.GetString(message.Data));
                };

                client.Start();
                Task.Delay(1000).Wait();

                for (int i = 0; i < 10; i++)
                {
                    client.Send("Hello " + i);
                    Task.Delay(250).Wait();
                }

                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
示例#15
0
 public void Start(string ip, int port)
 {
     try
     {
         _client = new WatsonTcpClient(ip, port)
         {
             ServerConnected = SuccessfullyСonnected,
             Debug           = false
         };
         _client.Start();
     }
     catch
     {
         MessageBox.Show(Properties.Resources.ServerNotAvaible, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
         _logger.LogError("Server is not available");
     }
 }
示例#16
0
        private static void ClientTask()
        {
            using (WatsonTcpClient client = new WatsonTcpClient("localhost", serverPort))
            {
                client.ServerConnected    = ClientServerConnected;
                client.ServerDisconnected = ClientServerDisconnected;
                client.MessageReceived    = ClientMsgReceived;
                client.Start();

                for (int i = 0; i < numIterations; i++)
                {
                    Task.Delay(rng.Next(0, 25)).Wait();
                    client.Send(data);
                }
            }

            Console.WriteLine("[client] finished");
        }
示例#17
0
        private static void InitializeClient()
        {
            if (!useSsl)
            {
                client = new WatsonTcpClient(serverIp, serverPort);
            }
            else
            {
                bool provideCertificate = Common.InputBoolean("Do you wish to provide a certificate ? (required for mutual authenication)", true);
                acceptInvalidCerts = Common.InputBoolean("Accept Invalid Certs:", true);

                if (provideCertificate)
                {
                    certFile             = Common.InputString("Certificate file:", "test.pfx", false);
                    certPass             = Common.InputString("Certificate password:"******"password", false);
                    mutualAuthentication = Common.InputBoolean("Mutually authenticate:", true);

                    client = new WatsonTcpClient(serverIp, serverPort, certFile, certPass)
                    {
                        AcceptInvalidCertificates = acceptInvalidCerts,
                        MutuallyAuthenticate      = mutualAuthentication,
                    };
                }
                else
                {
                    client = new WatsonTcpClient(Mode.Ssl, serverIp, serverPort, null)
                    {
                        AcceptInvalidCertificates = acceptInvalidCerts,
                    };
                }
            }

            client.AuthenticationFailure   = AuthenticationFailure;
            client.AuthenticationRequested = AuthenticationRequested;
            client.AuthenticationSucceeded = AuthenticationSucceeded;
            client.ServerConnected         = ServerConnected;
            client.ServerDisconnected      = ServerDisconnected;
            client.MessageReceived         = MessageReceived;
            client.ReadDataStream          = true;
            client.ReadStreamBufferSize    = 65536;
            // client.Debug = true;
            client.Start();
        }
示例#18
0
        /// <summary>
        /// Establish TCP (with or without SSL) connection to the peer server.
        /// </summary>
        public void Start()
        {
            if (Peer.Ssl)
            {
                _TcpClient = new WatsonTcpClient(
                    Peer.Ip,
                    Peer.Port,
                    Peer.PfxCertificateFile,
                    Peer.PfxCertificatePassword);
            }
            else
            {
                _TcpClient = new WatsonTcpClient(
                    Peer.Ip,
                    Peer.Port);
            }

            _TcpClient.AcceptInvalidCertificates = _Settings.AcceptInvalidCertificates;
            _TcpClient.Debug = _Settings.Debug;
            _TcpClient.MutuallyAuthenticate = _Settings.MutuallyAuthenticate;
            _TcpClient.ReadDataStream       = _Settings.ReadDataStream;
            _TcpClient.ReadStreamBufferSize = _Settings.ReadStreamBufferSize;

            _TcpClient.AuthenticationRequested = MeshClientAuthenticationRequested;
            _TcpClient.AuthenticationSucceeded = MeshClientAuthenticationSucceeded;
            _TcpClient.AuthenticationFailure   = MeshClientAuthenticationFailure;
            _TcpClient.ServerConnected         = MeshClientServerConnected;
            _TcpClient.ServerDisconnected      = MeshClientServerDisconnected;
            _TcpClient.StreamReceived          = MeshClientStreamReceived;
            _TcpClient.MessageReceived         = MeshClientMessageReceived;

            try
            {
                _TcpClient.Start();
            }
            catch (Exception)
            {
                Task.Run(() => MeshClientServerDisconnected());
            }
        }
示例#19
0
        private void Test2ClientWorker()
        {
            using (WatsonTcpClient client = new WatsonTcpClient("127.0.0.1", 10000))
            {
                client.MessageReceived = Test2ClientMsgRcv;
                client.Start();

                for (int i = 0; i < _NumMessages; i++)
                {
                    if (client.Send(_MsgBytes))
                    {
                        _MessageSuccess++;
                        _BytesSent += _MsgBytes.Length;
                    }
                    else
                    {
                        _MessageFailed++;
                    }
                }
            }

            _RunningTasks--;
        }
示例#20
0
        private void Test2ClientWorker(int clientNum)
        {
            try
            {
                long msgsSent  = 0;
                long bytesSent = 0;

                using (WatsonTcpClient client = new WatsonTcpClient("127.0.0.1", 10000))
                {
                    client.Events.MessageReceived += Test2ClientMsgRcv;
                    client.Start();

                    for (int i = 0; i < _NumMessages; i++)
                    {
                        if (client.Send(_MsgBytes))
                        {
                            msgsSent++;
                            bytesSent += _MsgBytes.Length;
                            Interlocked.Increment(ref _MessagesSentSuccess);
                            Interlocked.Increment(ref _MessagesProcessing);
                            Interlocked.Add(ref _BytesSent, _MsgBytes.Length);
                        }
                        else
                        {
                            Interlocked.Increment(ref _MessagesSentFailed);
                        }
                    }
                }

                Interlocked.Decrement(ref _RunningTasks);
                Console.WriteLine("Client " + clientNum + " finished, sent " + msgsSent + " messages, " + bytesSent + " bytes");
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.ToString());
            }
        }
示例#21
0
        private static void ClientTask()
        {
            Console.WriteLine("ClientTask entering");
            using (WatsonTcpClient client = new WatsonTcpClient("localhost", serverPort))
            {
                client.ServerConnected    = ClientServerConnected;
                client.ServerDisconnected = ClientServerDisconnected;
                client.MessageReceived    = ClientMsgReceived;
                client.Start();

                while (!clientsStarted)
                {
                    Thread.Sleep(100);
                }

                for (int i = 0; i < numIterations; i++)
                {
                    Task.Delay(rng.Next(0, 1000)).Wait();
                    client.Send(data);
                }
            }

            Console.WriteLine("[client] finished");
        }
示例#22
0
        static void Main(string[] args)
        {
            server = new WatsonTcpServer("127.0.0.1", 9000);
            server.Events.ClientConnected    += ServerClientConnected;
            server.Events.ClientDisconnected += ServerClientDisconnected;
            server.Events.MessageReceived    += ServerMessageReceived;
            // server.StreamReceived = ServerStreamReceived;
            // server.Debug = true;
            server.Start();

            client = new WatsonTcpClient("127.0.0.1", 9000);
            client.Events.ServerConnected    += ServerConnected;
            client.Events.ServerDisconnected += ServerDisconnected;
            client.Events.MessageReceived    += MessageReceived;
            // client.Events.StreamReceived = StreamReceived;
            // client.Debug = true;
            client.Start();

            int msgSize = (1024 * 128);

            Console.Write("Message size (default 128KB): ");
            string userInput = Console.ReadLine();

            if (!String.IsNullOrEmpty(userInput))
            {
                msgSize = Convert.ToInt32(userInput);
            }

            int msgCount = 4;

            Console.Write("Message count (default 4): ");
            userInput = Console.ReadLine();
            if (!String.IsNullOrEmpty(userInput))
            {
                msgCount = Convert.ToInt32(userInput);
            }

            Console.WriteLine("");
            Console.WriteLine("---");
            Console.WriteLine("Sending messages from client to server...");

            for (int i = 0; i < msgCount; i++)
            {
                string randomString = RandomString(msgSize);
                string md5          = Md5(randomString);
                Console.WriteLine("Client sending " + msgSize + " bytes: MD5 " + md5);
                client.Send(Encoding.UTF8.GetBytes(randomString));
            }

            Console.WriteLine("");
            Console.WriteLine("---");

            string ipPort = server.ListClients().ToList()[0];

            Console.WriteLine("Sending messages from server to client " + ipPort + "...");

            for (int i = 0; i < msgCount; i++)
            {
                string randomString = RandomString(msgSize);
                string md5          = Md5(randomString);
                Console.WriteLine("Server sending " + msgSize + " bytes: MD5 " + md5);
                server.Send(ipPort, Encoding.UTF8.GetBytes(randomString));
            }

            Console.WriteLine("");
            Console.WriteLine("---");
            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();
            server.Dispose();
            client.Dispose();
        }
示例#23
0
        private static void ClientToServer()
        {
            _Random         = new Random((int)DateTime.Now.Ticks);
            _DataLargeBytes = InitByteArray(_DataLargeSize, 0x00);
            _DataLargeMd5   = BytesToHex(Md5(_DataLargeBytes));
            _DataSmallBytes = InitByteArray(_DataSmallSize, 0x00);
            _DataSmallMd5   = BytesToHex(Md5(_DataSmallBytes));
            Console.WriteLine("Large Data MD5: " + _DataLargeMd5);
            Console.WriteLine("Small Data MD5: " + _DataSmallMd5);
            Console.WriteLine("Starting in 3 seconds...");

            _Server = new WatsonTcpServer(null, _ServerPort);
            _Server.Events.ClientConnected    += ServerClientConnected;
            _Server.Events.ClientDisconnected += ServerClientDisconnected;
            if (!_UseStreams)
            {
                _Server.Events.MessageReceived += ServerMsgReceived;
            }
            else
            {
                _Server.Events.StreamReceived += ServerStreamReceived;
            }
            _Server.Callbacks.SyncRequestReceived = ServerSyncRequestReceived;
            _Server.Settings.MaxProxiedStreamSize = _MaxProxiedStreamSize;
            _Server.Settings.Logger        = Console.WriteLine;
            _Server.Settings.DebugMessages = _Debug;
            _Server.Start();

            Thread.Sleep(2000);

            _Client = new WatsonTcpClient("localhost", _ServerPort);
            _Client.Events.ServerConnected    += ClientServerConnected;
            _Client.Events.ServerDisconnected += ClientServerDisconnected;
            if (!_UseStreams)
            {
                _Client.Events.MessageReceived += ClientMsgReceived;
            }
            else
            {
                _Client.Events.StreamReceived += ClientStreamReceived;
            }
            _Client.Callbacks.SyncRequestReceived = ClientSyncRequestReceived;
            _Client.Settings.MaxProxiedStreamSize = _MaxProxiedStreamSize;
            _Client.Settings.Logger        = Console.WriteLine;
            _Client.Settings.DebugMessages = _Debug;
            _Client.Start();

            Thread.Sleep(2000);

            Console.WriteLine("Press ENTER to exit");

            for (int i = 0; i < _ClientThreads; i++)
            {
                Console.WriteLine("Starting client thread " + i);
                Task.Run(() => ClientTask());
            }

            Console.WriteLine("Press ENTER after completion to view statistics");
            Console.ReadLine();

            Console.WriteLine("Success: " + _Success);
            Console.WriteLine("Failure: " + _Failure);
        }
示例#24
0
        private static void Main(string[] args)
        {
            InitializeClient();

            bool runForever = true;
            Dictionary <object, object> metadata;
            bool success;

            while (runForever)
            {
                string userInput = InputString("Command [? for help]:", null, false);

                switch (userInput)
                {
                case "?":
                    Console.WriteLine("Available commands:");
                    Console.WriteLine("  ?                   help (this menu)");
                    Console.WriteLine("  q                   quit");
                    Console.WriteLine("  cls                 clear screen");
                    Console.WriteLine("  send                send message to server");
                    Console.WriteLine("  send md             send message with metadata to server");
                    Console.WriteLine("  sendasync           send message to server asynchronously");
                    Console.WriteLine("  sendasync md        send message with metadata to server asynchronously");
                    Console.WriteLine("  sendandwait         send message and wait for a response");
                    Console.WriteLine("  sendempty           send empty message with metadata");
                    Console.WriteLine("  sendandwait empty   send empty message with metadata and wait for a response");
                    Console.WriteLine("  status              show if client connected");
                    Console.WriteLine("  dispose             dispose of the connection");
                    Console.WriteLine("  connect             connect to the server if not connected");
                    Console.WriteLine("  reconnect           disconnect if connected, then reconnect");
                    Console.WriteLine("  psk                 set the preshared key");
                    Console.WriteLine("  auth                authenticate using the preshared key");
                    Console.WriteLine("  stats               display client statistics");
                    Console.WriteLine("  stats reset         reset statistics other than start time and uptime");
                    Console.WriteLine("  comp                set the compression type, currently: " + client.Compression.ToString());
                    Console.WriteLine("  debug               enable/disable debug (currently " + client.DebugMessages + ")");
                    break;

                case "q":
                    runForever = false;
                    break;

                case "cls":
                    Console.Clear();
                    break;

                case "send":
                    userInput = InputString("Data:", null, false);
                    if (!client.Send(Encoding.UTF8.GetBytes(userInput)))
                    {
                        Console.WriteLine("Failed");
                    }
                    break;

                case "send md":
                    userInput = InputString("Data:", null, false);
                    metadata  = InputDictionary();
                    if (!client.Send(metadata, Encoding.UTF8.GetBytes(userInput)))
                    {
                        Console.WriteLine("Failed");
                    }
                    break;

                case "send md large":
                    metadata = new Dictionary <object, object>();
                    for (int i = 0; i < 100000; i++)
                    {
                        metadata.Add(i, i);
                    }
                    if (!client.Send(metadata, "Hello!"))
                    {
                        Console.WriteLine("Failed");
                    }
                    break;

                case "sendasync":
                    userInput = InputString("Data:", null, false);
                    success   = client.SendAsync(Encoding.UTF8.GetBytes(userInput)).Result;
                    if (!success)
                    {
                        Console.WriteLine("Failed");
                    }
                    break;

                case "sendasync md":
                    userInput = InputString("Data:", null, false);
                    metadata  = InputDictionary();
                    success   = client.SendAsync(metadata, Encoding.UTF8.GetBytes(userInput)).Result;
                    if (!success)
                    {
                        Console.WriteLine("Failed");
                    }
                    break;

                case "sendandwait":
                    SendAndWait();
                    break;

                case "sendempty":
                    metadata = InputDictionary();
                    success  = client.Send(metadata);
                    if (!success)
                    {
                        Console.WriteLine("Failed");
                    }
                    break;

                case "sendandwait empty":
                    SendAndWaitEmpty();
                    break;

                case "status":
                    if (client == null)
                    {
                        Console.WriteLine("Connected: False (null)");
                    }
                    else
                    {
                        Console.WriteLine("Connected: " + client.Connected);
                    }

                    break;

                case "dispose":
                    client.Dispose();
                    break;

                case "connect":
                    if (client != null && client.Connected)
                    {
                        Console.WriteLine("Already connected");
                    }
                    else
                    {
                        client = new WatsonTcpClient(serverIp, serverPort);
                        client.ServerConnected    += ServerConnected;
                        client.ServerDisconnected += ServerDisconnected;
                        client.MessageReceived    += MessageReceived;
                        client.Start();
                    }
                    break;

                case "reconnect":
                    ConnectClient();
                    break;

                case "psk":
                    presharedKey = InputString("Preshared key:", "1234567812345678", false);
                    break;

                case "auth":
                    client.Authenticate(presharedKey);
                    break;

                case "stats":
                    Console.WriteLine(client.Stats.ToString());
                    break;

                case "stats reset":
                    client.Stats.Reset();
                    break;

                case "comp":
                    client.Compression = (CompressionType)(Enum.Parse(typeof(CompressionType), InputString("Compression [None|Default|Gzip]:", "None", false)));
                    break;

                case "debug":
                    client.DebugMessages = !client.DebugMessages;
                    Console.WriteLine("Debug set to: " + client.DebugMessages);
                    break;

                default:
                    break;
                }
            }
        }
示例#25
0
 private void button1_Click(object sender, EventArgs e)
 {
     _Client.Start();
 }
示例#26
0
        private void MaintainConnection()
        {
            while (true)
            {
                try
                {
                    if (_WtcpClient == null)
                    {
                        if (Debug)
                        {
                            Log("Attempting connection to " + _ServerIp + ":" + _ServerPort);
                        }

                        if (String.IsNullOrEmpty(_CertFile))
                        {
                            _WtcpClient = new WatsonTcpClient(_ServerIp, _ServerPort);
                        }
                        else
                        {
                            _WtcpClient = new WatsonTcpClient(_ServerIp, _ServerPort, _CertFile, _CertPass);
                        }

                        _WtcpClient.Debug                     = Debug;
                        _WtcpClient.ReadDataStream            = false;
                        _WtcpClient.ReadStreamBufferSize      = ReadStreamBufferSize;
                        _WtcpClient.AcceptInvalidCertificates = AcceptInvalidCertificates;
                        _WtcpClient.MutuallyAuthenticate      = MutuallyAuthenticate;

                        _WtcpClient.AuthenticationRequested = AuthenticationRequested;
                        _WtcpClient.AuthenticationSucceeded = AuthenticationSucceeded;
                        _WtcpClient.AuthenticationFailure   = AuthenticationFailed;

                        _WtcpClient.ServerConnected    = ServerConnected;
                        _WtcpClient.ServerDisconnected = ServerDisconnected;
                        _WtcpClient.StreamReceived     = StreamReceived;

                        _WtcpClient.Start();
                    }
                    else if (!_WtcpClient.Connected)
                    {
                        if (String.IsNullOrEmpty(_CertFile))
                        {
                            _WtcpClient = new WatsonTcpClient(_ServerIp, _ServerPort);
                        }
                        else
                        {
                            _WtcpClient = new WatsonTcpClient(_ServerIp, _ServerPort, _CertFile, _CertPass);
                        }

                        _WtcpClient.Debug                     = Debug;
                        _WtcpClient.ReadDataStream            = false;
                        _WtcpClient.ReadStreamBufferSize      = ReadStreamBufferSize;
                        _WtcpClient.AcceptInvalidCertificates = AcceptInvalidCertificates;
                        _WtcpClient.MutuallyAuthenticate      = MutuallyAuthenticate;

                        _WtcpClient.AuthenticationRequested = AuthenticationRequested;
                        _WtcpClient.AuthenticationSucceeded = AuthenticationSucceeded;
                        _WtcpClient.AuthenticationFailure   = AuthenticationFailed;

                        _WtcpClient.ServerConnected    = ServerConnected;
                        _WtcpClient.ServerDisconnected = ServerDisconnected;
                        _WtcpClient.StreamReceived     = StreamReceived;

                        if (Debug)
                        {
                            Log("Attempting reconnect to " + _ServerIp + ":" + _ServerPort);
                        }

                        _WtcpClient.Start();
                    }

                    Task.Delay(1000).Wait();
                }
                catch (SocketException)
                {
                    Log("Unable to connect to peer");
                }
                catch (Exception e)
                {
                    if (Debug)
                    {
                        LogException("MaintainConnection", e);
                    }
                }
            }
        }
示例#27
0
        internal void RunTest()
        {
            try
            {
                using (WatsonTcpServer server = new WatsonTcpServer("127.0.0.1", 10000))
                {
                    server.Events.MessageReceived += Test1ServerMsgRcv;
                    server.Start();
                    // server.Settings.Logger = ServerLogger;
                    // server.Debug = true;

                    using (WatsonTcpClient client = new WatsonTcpClient("127.0.0.1", 10000))
                    {
                        client.Events.MessageReceived += Test1ClientMsgRcv;
                        client.Start();

                        _Stopwatch.Start();

                        for (int i = 0; i < _NumMessages; i++)
                        {
                            if (client.Send(_MsgBytes))
                            {
                                Interlocked.Increment(ref _MessagesSentSuccess);
                                Interlocked.Increment(ref _MessagesProcessing);
                                Interlocked.Add(ref _BytesSent, _MessageSize);
                            }
                            else
                            {
                                Interlocked.Increment(ref _MessagesSentFailed);
                            }
                        }

                        _Stopwatch.Stop();

                        decimal secondsTotal = _Stopwatch.ElapsedMilliseconds / 1000;
                        if (secondsTotal < 1)
                        {
                            secondsTotal = 1;
                        }

                        Console.WriteLine("Messages sent after " + secondsTotal + " seconds");
                        while (_MessagesProcessing > 0)
                        {
                            Console.WriteLine("Waiting on " + _MessagesProcessing + " to complete processing (1 second pause)");
                            Thread.Sleep(1000);
                        }

                        Console.WriteLine("");
                        Console.WriteLine("Results:");
                        Console.WriteLine("  Messages sent successfully     : " + _MessagesSentSuccess);
                        Console.WriteLine("  Messages failed                : " + _MessagesSentFailed);
                        Console.WriteLine("  Bytes sent successfully        : " + _BytesSent);
                        Console.WriteLine("  Bytes received successfully    : " + _BytesReceived);

                        decimal bytesPerSecond = _BytesSent / secondsTotal;
                        decimal kbPerSecond    = bytesPerSecond / 1024;
                        decimal mbPerSecond    = kbPerSecond / 1024;
                        Console.WriteLine("  Elapsed time sending (ms)      : " + _Stopwatch.ElapsedMilliseconds + "ms");
                        Console.WriteLine("  Elapsed time sending (seconds) : " + decimal.Round(secondsTotal, 2) + "s");
                        Console.WriteLine("  Send bytes per second          : " + decimal.Round(bytesPerSecond, 2) + "B/s");
                        Console.WriteLine("  Send kilobytes per second      : " + decimal.Round(kbPerSecond, 2) + "kB/s");
                        Console.WriteLine("  Send megabytes per second      : " + decimal.Round(mbPerSecond, 2) + "MB/s");
                        Console.WriteLine("");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.ToString());
            }
        }
示例#28
0
        static void Main(string[] args)
        {
            using (server = new WatsonTcpServer(serverHostname, serverPort))
            {
                server.ClientConnected += (s, e) =>
                {
                    Console.WriteLine("Client connected to server: " + e.IpPort);
                    clientIpPort = e.IpPort;
                };

                server.ClientDisconnected += (s, e) =>
                {
                    Console.WriteLine("Client disconnected from server: " + e.IpPort);
                    clientIpPort = null;
                };

                server.MessageReceived += (s, e) =>
                {
                    Console.WriteLine("Server received message from client " + e.IpPort + ": " + Encoding.UTF8.GetString(e.Data));
                };

                server.SyncRequestReceived = delegate(SyncRequest req)
                {
                    Console.WriteLine("Server received sync message from client " + req.IpPort + ": " + Encoding.UTF8.GetString(req.Data));
                    return(new SyncResponse(req, "Here's your response from the server!"));
                };

                server.Logger = ServerLogger;
                server.Start();

                using (client = new WatsonTcpClient(serverHostname, serverPort))
                {
                    client.ServerConnected += (s, e) =>
                    {
                        Console.WriteLine("Client connected to server");
                    };

                    client.ServerDisconnected += (s, e) =>
                    {
                        Console.WriteLine("Client disconnected from server");
                    };

                    client.MessageReceived += (s, e) =>
                    {
                        Console.WriteLine("Client received message from server: " + Encoding.UTF8.GetString(e.Data));
                    };

                    client.SyncRequestReceived = delegate(SyncRequest req)
                    {
                        Console.WriteLine("Client received sync message from server: " + Encoding.UTF8.GetString(req.Data));
                        return(new SyncResponse(req, "Here's your response from the client!"));
                    };

                    client.Logger = ClientLogger;
                    client.Start();

                    while (true)
                    {
                        Task.Delay(5000).Wait();
                        Task.Run(() => ServerTask());
                        Task.Run(() => ClientTask());
                    }
                }
            }
        }
示例#29
0
        public void InitClient()
        {
            messageIdentifier  = "msg";
            usernameIdentifier = "usr";
            splitCharacter     = '|';
            bool  validUsername;
            Regex regex = new Regex("^[a-zA-Z0-9_-]+$");

            do
            {
                Console.WriteLine("Please enter your username:"******"192.168.209.7", 9000);

            client.ServerConnected    = ServerConnected;
            client.ServerDisconnected = ServerDisconnected;
            client.MessageReceived    = MessageReceived;
            client.Debug = false;
            client.Start();
            client.Send(Encoding.UTF8.GetBytes(usernameIdentifier + splitCharacter + clientName));

            bool runForever = true;

            while (runForever)
            {
                Console.WriteLine("Command [q cls send auth]: ");
                string userInput = Console.ReadLine();
                if (string.IsNullOrEmpty(userInput))
                {
                    continue;
                }

                switch (userInput)
                {
                case "q":
                    runForever = false;
                    break;

                case "cls":
                    Console.Clear();
                    break;

                case "send":
                    Console.Write("Data: ");
                    userInput = Console.ReadLine();
                    if (string.IsNullOrEmpty(userInput))
                    {
                        break;
                    }
                    client.Send(Encoding.UTF8.GetBytes(messageIdentifier + splitCharacter + userInput));
                    break;

                case "auth":
                    Console.Write("Preshared key: ");
                    userInput = Console.ReadLine();
                    if (string.IsNullOrEmpty(userInput))
                    {
                        break;
                    }
                    client.Authenticate(userInput);
                    break;
                }
            }
        }
示例#30
0
        private static void Main(string[] args)
        {
            serverIp   = InputString("Server IP:", "127.0.0.1", false);
            serverPort = InputInteger("Server port:", 9000, true, false);
            useSsl     = InputBoolean("Use SSL:", false);

            InitializeClient();

            bool runForever = true;
            Dictionary <object, object> metadata;
            bool success;

            while (runForever)
            {
                Console.Write("Command [? for help]: ");
                string       userInput = Console.ReadLine();
                byte[]       data      = null;
                MemoryStream ms        = null;

                if (String.IsNullOrEmpty(userInput))
                {
                    continue;
                }

                switch (userInput)
                {
                case "?":
                    Console.WriteLine("Available commands:");
                    Console.WriteLine("  ?              help (this menu)");
                    Console.WriteLine("  q              quit");
                    Console.WriteLine("  cls            clear screen");
                    Console.WriteLine("  send           send message to server");
                    Console.WriteLine("  send md        send message with metadata to server");
                    Console.WriteLine("  sendasync      send message to server asynchronously");
                    Console.WriteLine("  sendasync md   send message with metadata to server asynchronously");
                    Console.WriteLine("  status         show if client connected");
                    Console.WriteLine("  dispose        dispose of the connection");
                    Console.WriteLine("  connect        connect to the server if not connected");
                    Console.WriteLine("  reconnect      disconnect if connected, then reconnect");
                    Console.WriteLine("  psk            set the preshared key");
                    Console.WriteLine("  auth           authenticate using the preshared key");
                    Console.WriteLine("  debug          enable/disable debug (currently " + client.DebugMessages + ")");
                    break;

                case "q":
                    runForever = false;
                    break;

                case "cls":
                    Console.Clear();
                    break;

                case "send":
                    Console.Write("Data: ");
                    userInput = Console.ReadLine();
                    if (String.IsNullOrEmpty(userInput))
                    {
                        break;
                    }
                    data    = Encoding.UTF8.GetBytes(userInput);
                    ms      = new MemoryStream(data);
                    success = client.Send(data.Length, ms);
                    Console.WriteLine(success);
                    break;

                case "send md":
                    metadata = InputDictionary();
                    Console.Write("Data: ");
                    userInput = Console.ReadLine();
                    if (String.IsNullOrEmpty(userInput))
                    {
                        break;
                    }
                    data    = Encoding.UTF8.GetBytes(userInput);
                    ms      = new MemoryStream(data);
                    success = client.Send(metadata, data.Length, ms);
                    Console.WriteLine(success);
                    break;

                case "sendasync":
                    Console.Write("Data: ");
                    userInput = Console.ReadLine();
                    if (String.IsNullOrEmpty(userInput))
                    {
                        break;
                    }
                    data    = Encoding.UTF8.GetBytes(userInput);
                    ms      = new MemoryStream(data);
                    success = client.SendAsync(data.Length, ms).Result;
                    Console.WriteLine(success);
                    break;

                case "sendasync md":
                    metadata = InputDictionary();
                    Console.Write("Data: ");
                    userInput = Console.ReadLine();
                    if (String.IsNullOrEmpty(userInput))
                    {
                        break;
                    }
                    data    = Encoding.UTF8.GetBytes(userInput);
                    ms      = new MemoryStream(data);
                    success = client.SendAsync(metadata, data.Length, ms).Result;
                    Console.WriteLine(success);
                    break;

                case "status":
                    if (client == null)
                    {
                        Console.WriteLine("Connected: False (null)");
                    }
                    else
                    {
                        Console.WriteLine("Connected: " + client.Connected);
                    }

                    break;

                case "dispose":
                    client.Dispose();
                    break;

                case "connect":
                    if (client != null && client.Connected)
                    {
                        Console.WriteLine("Already connected");
                    }
                    else
                    {
                        client = new WatsonTcpClient(serverIp, serverPort);
                        client.ServerConnected    += ServerConnected;
                        client.ServerDisconnected += ServerDisconnected;
                        client.StreamReceived     += StreamReceived;
                        client.Start();
                    }
                    break;

                case "reconnect":
                    if (client != null)
                    {
                        client.Dispose();
                    }
                    client = new WatsonTcpClient(serverIp, serverPort);
                    client.ServerConnected    += ServerConnected;
                    client.ServerDisconnected += ServerDisconnected;
                    client.StreamReceived     += StreamReceived;
                    client.Start();
                    break;

                case "psk":
                    presharedKey = InputString("Preshared key:", "1234567812345678", false);
                    break;

                case "auth":
                    client.Authenticate(presharedKey);
                    break;

                case "debug":
                    client.DebugMessages = !client.DebugMessages;
                    Console.WriteLine("Debug set to: " + client.DebugMessages);
                    break;

                default:
                    break;
                }
            }
        }