private void Connect(ClientConnection connection) { if (connection.Client.State == ClientState.Disconnected) { connection.Connect(); } }
public static void Send(string server, int port, IMessage message) { ClientConnection connection = new ClientConnection(); connection.Connect(server, port); connection.Send(message); connection.Disconnect(); }
public void Run(string command) { string[] args = command.Trim().Split(' '); string host = args[0]; int port = int.Parse(args[1]); ClientMessage.Info($"Connecting to {host}:{port}..."); ClientConnection.Connect(host, port); }
public static T Send <T>(string server, int port, IMessage message) where T : IMessage { ClientConnection connection = new ClientConnection(); connection.Connect(server, port); T response = connection.Send <T>(message); connection.Disconnect(); return(response); }
public static T Send <T>(string server, int port, int txRxTimeout, IMessage message) where T : IMessage { SocketTransport transport = new SocketTransport { SendTimeout = txRxTimeout, ReceiveTimeout = txRxTimeout }; ClientConnection connection = new ClientConnection(transport); connection.Connect(server, port); T response = connection.Send <T>(message); connection.Disconnect(); return(response); }
public bool Connect(string address, int port) { if (mClientConnection.IsConnected() == 1) { return(true); } bool isConnected = mClientConnection.Connect(address, port); if (isConnected) { mMessageSchedulerTask = mScheduler.StartCoroutine(MessageScheduler()); } return(isConnected); }
public void When_connecting_to_the_server_endpoint_will_get_error() { var configuration = new InMemoryRavenConfiguration { RunInMemory = true }; configuration.Initialize(); using (new RavenMqServer(configuration)) using (var c = new ClientConnection(new IPEndPoint(IPAddress.Loopback, 8181), new CaptureClientIntegration())) { var e = Assert.Throws <AggregateException>(() => c.Connect().Wait()); Assert.Equal("Invalid response signature from server", e.InnerException.Message); } }
public void Can_get_notificaton_from_server() { connection.Start(); var clientIntegration = new CaptureClientIntegration(); using (var clientConnection = new ClientConnection(new IPEndPoint(IPAddress.Loopback, 8181), clientIntegration)) { clientConnection.Connect().Wait(); clientIntegration.MessageArrived.WaitOne(); Assert.Equal("{\"Pong\":\"Ping\"}", clientIntegration.Msgs[0].ToString(Formatting.None)); } }
//========== CONNECTION ========== #region Connection /**<summary>Attempts to connect to the host.</summary>*/ private void ClientConnect() { // Validate input int port = Config.Syncing.ClientPort; IPAddress ip = IPAddress.Loopback; if (Config.Syncing.ClientIPAddress != "" && !IPAddress.TryParse(Config.Syncing.ClientIPAddress, out ip)) { TriggerMessageBox.Show(this, MessageIcon.Warning, "The entered IP address in invalid!", "Invalid IP"); return; } if (Config.Syncing.ClientUsername == "") { TriggerMessageBox.Show(this, MessageIcon.Warning, "Cannot connect with an empty username!", "Invalid Username"); return; } // Connect to the host client = new ClientConnection(); client.MessageReceived += OnClientMessageReceived; client.ConnectionLost += OnClientConnectionLost; if (!client.Connect(ip, port)) { TriggerMessageBox.Show(this, MessageIcon.Warning, "Failed to connect to server!", "Connection Failed"); client = null; } else { // Final setup before waiting to login // Set the control states Dispatcher.Invoke(() => { comboBoxSyncType.IsEnabled = false; textBoxClientIP.IsEnabled = false; numericClientPort.IsEnabled = false; textBoxClientUsername.IsEnabled = false; textBoxClientPassword.IsEnabled = false; textBoxClientNextSong.IsEnabled = false; buttonClientConnect.IsEnabled = false; buttonClientConnect.Content = "Connecting..."; }); clientTimeout.Start(); client.Send(new StringCommand(Commands.Login, Config.Syncing.ClientUsername, Config.Syncing.ClientPassword)); } }
private void btnConnect_Click(object sender, EventArgs e) { if (!_connection.IsConnected) { ipAddress = cmbIPAddresses.Text; _connection.Connect(ipAddress, Port); if (_connection.IsConnected) { Properties.Settings.Default.IPanalyzer = ipAddress; Properties.Settings.Default.Save(); //persist ipaddress that works chkEnableSignalGenerator.Enabled = true; // Enable checkbox; _signalGenator.Enabled = false; btnConnect.Text = "Disconnect"; btnConnect.BackColor = Color.LightGreen; btnStartAcquisition.Enabled = true; btnSinleShot.Enabled = true; cmbIPAddresses.Enabled = false; btnFindDevices.Enabled = false; } else { MessageBox.Show("Could not connect.", "Connection", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { _analyzer.Stop(); _connection.Disconnect(); btnConnect.Text = "Connect"; btnConnect.BackColor = Color.Gainsboro; _analyzer.AcquireState = AcquireStates.Stopped; btnStartAcquisition.Text = "Stop"; btnStartAcquisition.BackColor = Color.Red; btnSinleShot.BackColor = Color.Gainsboro; btnStartAcquisition.Enabled = false; _signalGenator.Enabled = false; chkEnableSignalGenerator.Checked = false; chkEnableSignalGenerator.Enabled = false; // Enable checkbox; btnSinleShot.Enabled = false; cmbIPAddresses.Enabled = true; btnFindDevices.Enabled = true; } }
public void Execute() { Debug.Log("Build Connection"); MenuManager menuManager = GetComponentInChildren <MenuManager>(true); clientConnection.Connect("127.0.0.1", 3456); connectionDispatcher.Start(); string username = usernameInput.text; string password = passwordInput.text; connectionDispatcher.SendPackage(new LoginRequest() { Username = username, Password = password }); Debug.Log("Waiting to receive Login Response Package"); LoginResponse packageData = connectionDispatcher.WaitForPackage <LoginResponse>().Result; // TODO: automate this LogPackageResponse(packageData, packageData.IsValidLogin); }
public void ConnectToServer(string ip, int port, string username) { if (Connection.Connected) { throw new InvalidOperationException("Already connected to a server!"); } Connection.Connect(ip, port); PacketRequestConnect pRequestConnect = new PacketRequestConnect(username); Connection.SendPacket(pRequestConnect); Interface = new DreamInterface(); SoundEngine = new NAudioSoundEngine(); ResourceManager = new DreamResourceManager(); StateManager = new DreamStateManager(); IconAppearances = new List <IconAppearance>(); ATOMs = new Dictionary <UInt32, ATOM>(); ScreenObjects = new List <ATOM>(); MainWindow.Hide(); _updateTimer.Start(); }
static void Main(string[] args) { Console.WriteLine("Welcome in Console.TicTacToe v.0.1 by Michal Jasiak...\r\n"); Console.WriteLine("Please give your name..."); var name = Console.ReadLine(); Console.WriteLine(string.Format("Hello {0},\r\ndo you want X or O?", name)); var mark = Console.ReadLine(); Console.WriteLine("Connecting..."); var connection = ClientConnection.Connect(_listeningAddress, _listeningPort); var connectionHandler = new ClientConnectionHandler(connection); connectionHandler.OnMessageReceived += connectionHandler_OnMessageReceived; var requestMessage = new RequestMessage { Data = JsonConvert.SerializeObject(new Player { Name = name, Mark = char.Parse(mark) }), Method = "player/add" }; connectionHandler.Send(JsonConvert.SerializeObject(requestMessage)); connectionHandler.StartListening(); string message = string.Empty; message = Console.ReadLine(); while (!message.Equals("exit")) { var choose = message.Split(' ')[0]; switch (choose) { case "newgame": { requestMessage = new RequestMessage { Data = string.Empty, Method = "game/start" }; connectionHandler.Send(requestMessage.Serialize()); break; } case "continue": { if (_currentGame != null) { Console.Clear(); BuildMap(_currentGame.Map); IsYourTurn(); } else { Console.WriteLine("You haven't started game yet. Write 'newgame' to start it."); } break; } case "move": { var isNumeric = int.TryParse(message.Split(' ')[1], out int destination); if (isNumeric) { bool isNumber1to9 = Enumerable.Range(1, 9).Contains(destination); if (isNumber1to9) { Move move = new Move { GameId = _currentGame.Id, Player = _currentPlayer, Destination = destination - 1 }; requestMessage = new RequestMessage { Data = JsonConvert.SerializeObject(move), Method = "game/move" }; connectionHandler.Send(requestMessage.Serialize()); break; } } Console.WriteLine("First parameter of 'move' should be number from 1-9"); break; } case "help": { Console.Clear(); Console.WriteLine("--- TicTacToe Help Menu ---"); Console.WriteLine(" - newgame | Starts new game."); if (_currentGame != null) { Console.WriteLine(" - continue | Continue game."); Console.WriteLine(" - move field_number | Set your mark on specified field."); } Console.WriteLine(" - help | Shows help menu"); Console.WriteLine(" - exit | Close game."); break; } default: { Console.WriteLine("Command doesn't exist"); break; } } message = Console.ReadLine(); } connectionHandler.Close(); Console.WriteLine("* Client has exited... *"); Console.Clear(); }
public bool OpenConnection() { try { client = new ClientConnection(ip, port); client.dataReceived += client_dataReceived; client.Connect(); } catch (Exception) { } return client.Connected; }
public void TryReconnecting() { if (disposed) { return; } var webRequest = WebRequest.Create(queueEndpointSubscriptionPort); connectToServerTask = Task.Factory.FromAsync <WebResponse>(webRequest.BeginGetResponse, webRequest.EndGetResponse, null) .ContinueWith(getPortResponseTask => { using (var response = getPortResponseTask.Result) using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream)) { var result = JObject.Load(new JsonTextReader(reader)); return(result.Value <int>("SubscriptionPort")); } }) .ContinueWith(getPortTask => { var result = getPortTask.Result; var hostAddresses = Dns.GetHostAddresses(queueEndpointSubscriptionPort.DnsSafeHost); return(new IPEndPoint(hostAddresses.First(x => x.AddressFamily == AddressFamily.InterNetwork), result)); }) .ContinueWith(subscriptionEndpointTask => { clientConnection = new ClientConnection(subscriptionEndpointTask.Result, this); return(clientConnection.Connect()); }) .Unwrap() .ContinueWith(task => { if (task.Exception != null) { return(task); } return(clientConnection.Send(JObject.FromObject(new ChangeSubscriptionMessage { Type = ChangeSubscriptionType.Set, Queues = new List <string>(lastEtagPerQeueue.Keys) }))); }) .Unwrap() .ContinueWith(task => { if (task.Exception != null) // retrying if we got an error { if (disposed) { return(task); } Console.WriteLine("Failure {0}", DateTime.Now); GC.Collect(2); GC.WaitForPendingFinalizers(); TaskEx.Delay(TimeSpan.FromSeconds(3)) .ContinueWith(_ => TryReconnecting()); return(task); } Console.WriteLine("Success"); // ask for latest return(UpdateAsync()); }) .Unwrap() .IgnoreExceptions(); }
static void Main(string[] args) { Thread.Sleep(2000); Console.Write("Connecting to ChannelListener..."); ClientConnection client = new ClientConnection(new PlainEnvelope(), new SocketTransport()); //TcpClient client = new TcpClient(); //client.Connect("localhost", port); client.ClientClosed += new EventHandler <DisconnectedArgs>(client_ClientClosed); client.MessageReceived += new EventHandler <MessageEventArgs>(client_MessageReceived); client.Connect("localhost", port); Console.WriteLine("connected!"); DateTime connectTime = DateTime.Now; Console.WriteLine(string.Format("Connected at {0}", connectTime)); int count = 1; while (true) { Dictionary <string, string> headers = new Dictionary <string, string>(); string command = ""; while (true) { command = Console.ReadLine(); headers.Clear(); while (true) { string line = Console.ReadLine(); // check for termination if (line.Length == 0) { break; } string[] pieces = line.Split(':'); headers.Add(pieces[0].ToUpper(), pieces[1].ToUpper()); } break; } MessageOne msg = new MessageOne(); msg.MessageID = "MessageOne"; msg.Value = 23; //scm.ControlMode = ControlMode.ChannelController; try { var env = client.Envelope; using (StreamWrapper wrapper = new StreamWrapper(client.Transport.Stream)) { env.Serialize(msg, wrapper); //((SocketTransport)client.Transport) //IMessage response = client.Send<Message>(msg); //Console.WriteLine(msg.Name); } } catch (Exception pex) { Console.WriteLine(pex.Message); } //CustomMessage message = new CustomMessage(command); //foreach (string key in headers.Keys) // message.AddKeyValue(key, headers[key]); //Message response; //{ // try // { // response = client.SendAndReceive(message); // Console.WriteLine("Message received: " + response.Name); // Console.WriteLine(response.ToString()); // } // catch (Exception ex) // { // Console.WriteLine(ex.Message + "\r\n"); // Console.WriteLine("Reconnecting..."); // Console.WriteLine(client.Connect()); // connectTime = DateTime.Now; // Console.WriteLine(string.Format("Connected at {0}", connectTime)); // } //} TimeSpan ts = DateTime.Now - connectTime; Console.WriteLine(string.Format(" connection open for {0:D2}:{1:D2}:{2:D2} [{3} messages processed]\r\n", ts.Hours, ts.Minutes, ts.Seconds, count++)); } }
public E <string> InitializeBot() { Log.Info("Bot ({0}) connecting to \"{1}\"", Id, config.Connect.Address); // Registering config changes config.CommandMatcher.Changed += (s, e) => { var newMatcher = Filter.GetFilterByName(e.NewValue); if (newMatcher.Ok) { Filter.Current = newMatcher.Value; } }; config.Language.Changed += (s, e) => { var langResult = LocalizationManager.LoadLanguage(e.NewValue); if (!langResult.Ok) { Log.Error("Failed to load language file ({0})", langResult.Error); } }; Injector.RegisterType <Bot>(); Injector.RegisterType <ConfBot>(); Injector.RegisterType <BotInjector>(); Injector.RegisterType <PlaylistManager>(); Injector.RegisterType <Ts3Client>(); Injector.RegisterType <SessionManager>(); Injector.RegisterType <HistoryManager>(); Injector.RegisterType <PlayManager>(); Injector.RegisterType <IPlayerConnection>(); Injector.RegisterType <IVoiceTarget>(); Injector.RegisterType <Ts3BaseFunctions>(); Injector.RegisterType <Filter>(); Injector.RegisterModule(this); Injector.RegisterModule(config); Injector.RegisterModule(Injector); Injector.RegisterModule(new PlaylistManager(config.Playlists)); var teamspeakClient = new Ts3Client(config); Injector.RegisterModule(teamspeakClient); Injector.RegisterModule(teamspeakClient.TsFullClient); Injector.RegisterModule(new SessionManager()); HistoryManager historyManager = null; if (config.History.Enabled) { Injector.RegisterModule(historyManager = new HistoryManager(config.History), x => x.Initialize()); } Injector.RegisterModule(new PlayManager()); Injector.RegisterModule(teamspeakClient.TargetPipe); var filter = Filter.GetFilterByName(config.CommandMatcher); Injector.RegisterModule(new Filter { Current = filter.OkOr(Filter.DefaultAlgorithm) }); if (!filter.Ok) { Log.Warn("Unknown command_matcher config. Using default."); } if (!Injector.AllResolved()) { Log.Warn("Cyclic bot module dependency"); Injector.ForceCyclicResolve(); if (!Injector.AllResolved()) { Log.Error("Missing bot module dependency"); return("Could not load all bot modules"); } } PlayerConnection.OnSongEnd += PlayManager.SongStoppedHook; PlayManager.BeforeResourceStarted += BeforeResourceStarted; // In own favor update the own status text to the current song title PlayManager.AfterResourceStarted += LoggedUpdateBotStatus; PlayManager.AfterResourceStopped += LoggedUpdateBotStatus; // Log our resource in the history if (historyManager != null) { PlayManager.AfterResourceStarted += (s, e) => historyManager.LogAudioResource(new HistorySaveData(e.PlayResource.BaseData, e.Invoker.ClientUid)); } // Update our thumbnail PlayManager.AfterResourceStarted += GenerateStatusImage; PlayManager.AfterResourceStopped += GenerateStatusImage; // Register callback for all messages happening ClientConnection.OnMessageReceived += TextCallback; // Register callback to remove open private sessions, when user disconnects ClientConnection.OnClientDisconnect += OnClientDisconnect; ClientConnection.OnBotConnected += OnBotConnected; ClientConnection.OnBotDisconnect += OnBotDisconnect; BadgesString = config.Connect.Badges; // Connect the query after everyting is set up return(ClientConnection.Connect()); }