public ClientConnectorTester() { theCommand = new RecordingCommand <RunSpec>(); theRemoteController = Substitute.For <IRemoteController>(); theConnector = new ClientConnector(new WebSocketsHandler(), theRemoteController, new ICommand[] { theCommand }); }
public void SetUp() { theCommand = new RecordingCommand <RunSpec>(); theRemoteController = MockRepository.GenerateMock <IRemoteController>(); theConnector = new ClientConnector(new RecordingLogger(), theRemoteController, new ICommand[] { theCommand }); }
public void Connect(string domain, int port) { if (!ipsCachedDictionary.ContainsKey(domain) || ipsCachedDictionary[domain].Expire < DateTime.UtcNow) { var ips = Dns.GetHostAddresses(domain); var ipsCached = new LJPDNSCache { Ips = ips, Expire = DateTime.UtcNow.AddSeconds(this.options.ExpirationDNSCache), Length = ips.Length, Current = 0 }; this.ipsCachedDictionary[domain] = ipsCached; } var currentIp = this.ipsCachedDictionary[domain].Current; var ip = this.ipsCachedDictionary[domain].Ips[currentIp]; try { ClientConnector.Connect(ip, port); } catch (SocketException) { var ipCached = this.ipsCachedDictionary[domain]; ipCached.Current = ipCached.Current < (ipCached.Ips.Length - 1) ? ++ipCached.Current : 0; throw; } }
public void SendCall(LJPCall sendCallParameter) { if (sendCallParameter == null) { SendResponse(null);//No Data } else { var messageExtractor = factoryClientLJP.CreateMessageFactory(sendCallParameter.Version); string jsonFinal = messageExtractor.Parse(sendCallParameter); string message = $"Version={sendCallParameter.Version}\n" + $"Length={Encoding.UTF8.GetBytes(jsonFinal).Length}\n" + $"Id={sendCallParameter.Id}\n" + $"KeepAlive={sendCallParameter.KeepAlive}\n" + $"NeedResponse={sendCallParameter.NeedResponse}\n" + $"Interface={sendCallParameter.InterfaceName}\n" + $"Method={sendCallParameter.MethodName}\n" + "\n" + $"{jsonFinal}"; #if DEBUG logger.Debug($"SendCall From [{ClientConnector.LocalEndPoint?.ToString() ?? ""}] To [{ClientConnector.RemoteEndPoint?.ToString() ?? ""}], Msg = {jsonFinal.Replace("\n", "[nl]")}"); #endif var aMessage = Encoding.UTF8.GetBytes(message); ClientConnector.Send(aMessage, 0, aMessage.Length); } }
LJPResponse ReceiveResponse(ICollection <Type> tpeNamespace, bool bThrowExceptionWithNotData = true) { //Receive Header Array.Clear(receiveBuffer, 0, receiveBuffer.Length); ClientConnector.Receive(receiveBuffer, 0, receiveBuffer.Length); return(ConvertToLJPResponse(tpeNamespace, receiveBuffer, bThrowExceptionWithNotData)); }
private void InitClientConnector() { _clientConnector = new ClientConnector(new ClientConnectorSettings() { PacketsMap = new Dictionary <Tuple <int, int>, Type>(_packetsMap), ServerAddressList = new List <Tuple <string, int> >() { new Tuple <string, int>(Program.AppSettingsClient.ServerAddress, 1112) } }); _clientConnector.OnPacket += ClientConnector_OnPacket; _clientConnector.OnConnect += ClientConnector_OnConnect; _clientConnector.OnDisconnect += ClientConnector_OnDisconnect; _clientConnector.OnException += ClientConnector_OnException; _clientConnector.OnDebugLog += ClientConnector_OnDebugLog; _clientConnector.Connect(); object loginResponse = null; try { loginResponse = _clientConnector.SendRequest(new LoginRequestPacket { Username = "******" }); } catch (Exception ex) { Console.WriteLine("Exception on first packet:" + ex.ToString()); } Console.WriteLine($"Response loginResponse:{JsonConvert.SerializeObject(loginResponse)}"); }
public bool ConnectToHost(string id, string password, string HostIp) { connector = new ClientConnector(id, password, 100, ConfigMgr.ServerIp, 9200, this); // GameController.LogToScreen("Connector Created"); Debug.Log("Connector Created"); connector.Start(); StartCoroutine(InteruptStallConnector()); while (connector.lastErr == eErrorCode.LOADING) { } if (connector.lastErr != eErrorCode.DONE) { GameController.LogToScreen("LoginFailed "); Debug.Log("LoginFailed " + connector.lastErr.ToString()); return(false); } PlayerPrefs.SetString("Id", id); PlayerPrefs.SetString("Pass", password + "123"); PlayerPrefs.SetString("Host", HostIp); PlayerPrefs.SetString("28102000", password); GameController.LogToScreen("Connector Started"); Debug.Log("Login Done - Connector Started"); ((CommonUIController)gameController.uiController).notiPanel.ShowText("Đang xử lý ... "); string decStr = connector.LoadTemplate(); XmlDocument document = new XmlDocument(); document.LoadXml(decStr); XmlNodeList itemNodes = document.GetElementsByTagName("Item"); StartCoroutine(ExecLoadTemplate(itemNodes)); StartCoroutine(UpdateLoadTemplateProcess()); isLogedIn = true; return(true); }
public Form1() { connector = new ClientConnector(port, address); connector.Connect(); InitializeComponent(); timer1.Interval = 3000; timer1.Start(); }
public void Disconnect(bool dispose = false) { ClientConnector?.Disconnect(dispose); if (dispose) { this.Dispose(); this.ClientConnector.Dispose(); } }
public bool ConnectToHost(string HostIp) { connector = new ClientConnector("bot0", "123456", 100, HostIp, 9200, this); GameController.LogToScreen("Connector Created"); Debug.Log("Connector Created"); connector.Start(); GameController.LogToScreen("Connector Started"); Debug.Log("Connector Started"); return(true); }
public virtual void Initialize() { this.RequestWriter = new RequestWriter(); this.Sequence = new MockSequence(); this.SessionFactory = new StubSessionFactory(this.Sequence, this.Mode, this.Async); var connector = new ClientConnector(this.SessionFactory, this.RequestWriter); this.Client = new Client(connector, this.SessionFactory.TcpClient.Object); }
public void checkForConnection() { ClientConnector client = new ClientConnector(port, address); client.Connect(); Assert.IsTrue(client.CheckForConnection()); ClientConnector client2 = new ClientConnector(port, address); Assert.IsFalse(client2.CheckForConnection()); }
public void TestWithoutServer() { try { ClientConnector client = new ClientConnector(12345, address); }catch (Exception e) { Assert.Fail(string.Format("Unexpected exception of type {0} caught: {1}", e.GetType(), e.Message)); } }
protected ClientConnectorTestsBase(ClientConnector connector = null) : base(dummyServer: true) { Connector = connector ?? new ClientConnector(SocketType.Stream, ProtocolType.Tcp, new SocketAsyncEventArgs()) { Address = Addr, Port = Port }; Connector.Connected += OnConnected; Connector.Failed += OnFailed; }
public async Task TestReceiveAsync() { ClientConnector client = new ClientConnector(port, address); client.Connect(); CancellationTokenSource source = new CancellationTokenSource(); SendToClientOfListener(); client.ReceiveMessage(source.Token); Thread.Sleep(10000); source.Cancel(); }
static void Main(string[] args) { Console.WriteLine("TestSimpleEchoClient"); _clientConnector = new ClientConnector(new ClientConnectorSettings() { PacketsMap = new Dictionary <Tuple <int, int>, Type>() { { new Tuple <int, int>(1, 1), typeof(string) }, }, ServerAddressList = new List <Tuple <string, int> >() { new Tuple <string, int>("127.0.0.1", 1112) } }); _clientConnector.OnPacket += ClientConnector_OnPacket; _clientConnector.OnConnect += ClientConnector_OnConnect; _clientConnector.OnDisconnect += ClientConnector_OnDisconnect; _clientConnector.OnException += ClientConnector_OnException; _clientConnector.OnDebugLog += ClientConnector_OnDebugLog; _clientConnector.Connect(); try { _clientConnector.Send(1, 1, "start"); } catch (Exception ex) { Console.WriteLine("Exception on first packet:" + ex.ToString()); } while (true) { try { Console.WriteLine("Enter Input"); var inputLine = Console.ReadLine(); if (inputLine == "exp") { _clientConnector.SendRequest(1, 1, inputLine); } else { _clientConnector.Send(1, 1, inputLine); } } catch (Exception ex) { Console.WriteLine("Exception:" + ex.ToString()); } } }
/// <summary> /// Creates a new <see cref="Client"/> instance. /// </summary> /// <param name="socketConnection"></param> protected Client(ClientConfiguration clientConfiguration) { ClientConfiguration = clientConfiguration; connector = new ClientConnector(this); connectSocketArgs = CreateSocketEventArgs(null); connectSocketArgs.RemoteEndPoint = NetworkHelper.CreateIPEndPoint(ClientConfiguration.Host, ClientConfiguration.Port); sendSocketArgs = CreateSocketEventArgs(null); sendSocketArgs.RemoteEndPoint = NetworkHelper.CreateIPEndPoint(ClientConfiguration.Host, ClientConfiguration.Port); receiveSocketArgs = CreateSocketEventArgs(1024); receiveSocketArgs.RemoteEndPoint = NetworkHelper.CreateIPEndPoint(ClientConfiguration.Host, ClientConfiguration.Port); }
public MainWindow() { InitializeComponent(); LogHelper.OnNewEntryAdded += LogHelper_OnNewEntryAdded; clientConnector = new ClientConnector(); if (!clientConnector.Initialize()) { return; } if (!Properties.Settings.Default.AutostartChanged && !AutostartHelper.AutoStartEnabled(Consts.AppName)) { AutostartHelper.ToggleStartup(Consts.AppName); } }
static void Main(string[] args) { var nonLockingSessionFactory = new NonLockingSessionFactory(); var sessionFactory = new SessionFactory(); var requestWriter = new RequestWriter(); var connector = new ClientConnector(nonLockingSessionFactory, requestWriter); using (var client = new Client(connector, new TcpClientAdapter())) { client.Configure(new Configuration("localhost", 1491, "SecretPassword", ConnectionMode.Search)); client.Connect(); using (var session = sessionFactory.Create(client)) { Console.WriteLine(".NET Sonic Terminal"); Console.WriteLine("Write .read to read next line from the server."); while (true) { while (true) { Console.Write($"W > "); var input = Console.ReadLine(); if (input.ToLower().Trim() == ".read") { break; } else if (!string.IsNullOrWhiteSpace(input)) { session.Write(input); break; } } var response = session.Read(); Console.WriteLine($"R > {response}"); if (response.StartsWith("ENDED")) { break; } } } } }
public async Task SendAsync() { ClientConnector client = new ClientConnector(port, address); client.Connect(); Message message = new Message("Abdulmueez", "Hello", DateTime.Now); client.SendAsync(message); Message value = await CheckClientOfListener(); Assert.AreEqual(value.Msg, message.Msg); Assert.AreEqual(value.UserName, message.UserName); Assert.AreEqual(value.time, message.time); message.Msg += "2"; client.SendAsync(message); value = await CheckClientOfListener(); Assert.AreEqual(value.Msg, message.Msg); Assert.AreEqual(value.UserName, message.UserName); Assert.AreEqual(value.time, message.time); }
public void SendResponse(object oObject) { if (oObject == null) { oObject = new LJPExceptionDTO() { Message = "No data", IClientLJPExceptionType = (int)LJPExceptionType.NoData }; } var type = oObject.GetType(); //DataContractJsonSerializer oJsonSerializer = new(type); //MemoryStream oMS = new(); //oJsonSerializer.WriteObject(oMS, oObject);//Deserialize the oObject into Memory Stream (oMS). //oMS.Position = 0; //string sJson = new StreamReader(oMS).ReadToEnd();//Read object deserialized. var json = JsonConvert.SerializeObject(oObject); int iLength = Encoding.UTF8.GetBytes(json).Length; string message = string.Format( "Length={0}\n" + "Type={1}\n" + "\n{2}" , iLength , !oObject.GetType().GetTypeInfo().IsGenericType ? oObject.GetType().Name : oObject.GetType().FullName , json ); #if DEBUG logger.Debug($"SendReponse [Lenght={iLength}] From [{ClientConnector.LocalEndPoint?.ToString() ?? ""}] - To [{ClientConnector.RemoteEndPoint?.ToString() ?? ""}] {json.Replace("\n", "[nl]")}"); #endif var aMessage = Encoding.UTF8.GetBytes(message); ClientConnector.Send(aMessage, 0, aMessage.Length); }
static void Main(string[] args) { Console.WriteLine("TcpConnectors.TestClient"); _clientConnector = new ClientConnector(new ClientConnectorSettings() { PacketsMap = SendPacketsUtils.GetServer2ClientMapping(Assembly.GetAssembly(typeof(LoginResponsePacket))), ServerAddressList = new List <Tuple <string, int> >() { new Tuple <string, int>("127.0.0.1", 1111) } }); _clientConnector.OnPacket += ClientConnector_OnPacket; _clientConnector.OnConnect += ClientConnector_OnConnect; _clientConnector.OnDisconnect += ClientConnector_OnDisconnect; _clientConnector.OnException += ClientConnector_OnException; _clientConnector.OnDebugLog += ClientConnector_OnDebugLog;; _clientConnector.Connect(); Thread.Sleep(-1); }
public ClientConnectorTests(ClientConnector connector) : base(connector) { }
public void Test() { ClientConnector client = new ClientConnector(port, address); client.Connect(); }
private void AcceptCallback(IAsyncResult ar) { if (!Info.Running) { return; } Socket s = (Socket)ar.AsyncState; try { Socket s_client = s.EndAccept(ar); int client_id = s_client.GetHashCode(); Clients.Add(new XClient(s_client, client_id)); XClient client = GetClientByID(client_id); if (client == null) { return; } //MessageBox.Show("Client conectado: " + client_id.ToString()); string ip_redirect = TBRedirectIP.Text; Uri uriResult; IPAddress ip; bool result = Uri.TryCreate(ip_redirect, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); if (result) { ip = Dns.GetHostAddresses(uriResult.Host)[0]; } else { IPAddress.TryParse(ip_redirect, out ip); } IPEndPoint direct = new IPEndPoint(ip, int.Parse(TBRedirectPort.Text)); ClientConnector conn = new ClientConnector(client, direct); client.conn = conn; Thread.Sleep(600); this.Invoke(new Action(() => { string s_ip = ((IPEndPoint)(client.s.RemoteEndPoint)).Address.ToString(); LBClients.Items.Add("[" + client.id + "] " + s_ip + " -> " + client.conn.ip.Address.ToString()); })); client.s.BeginReceive(client.buff, 0, XClient.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), client); } catch (Exception e) { MessageBox.Show(e.ToString()); return; } finally { if (Info.Running) { s.BeginAccept(new AsyncCallback(AcceptCallback), s); } } }
public ProgressSummary GetProgressTotal(EServiceType serviceType) { return(ClientConnector.GetProgressTotal(serviceType)); }
public bool Login(string userName, string password) { return(ClientConnector.Login(userName, password)); }
public ProgressItem GetProgressUserTotal(EServiceType serviceType, string sellerAccount) { return(ClientConnector.GetProgressUserTotal(serviceType, sellerAccount)); }
static void Main(string[] args) { Console.WriteLine("TestRequestMultiResponseClient"); var serverIp = "127.0.0.1"; //var serverIp = "83.151.199.77"; _clientConnector = new ClientConnector(new ClientConnectorSettings() { PacketsMap = new Dictionary <Tuple <int, int>, Type>() { { new Tuple <int, int>(1, 1), typeof(GetListResponsePacket) }, { new Tuple <int, int>(1, 2), typeof(GetListResponsePacket) }, }, ServerAddressList = new List <Tuple <string, int> >() { new Tuple <string, int>(serverIp, 1112) } }); _clientConnector.OnPacket += ClientConnector_OnPacket; _clientConnector.OnConnect += ClientConnector_OnConnect; _clientConnector.OnDisconnect += ClientConnector_OnDisconnect; _clientConnector.OnException += ClientConnector_OnException; _clientConnector.OnDebugLog += ClientConnector_OnDebugLog; _clientConnector.Connect(); while (true) { try { Console.WriteLine("Enter Input (r-request, m-request multi response, x - test RequestMultiResponsesHandler)"); var inputLine = Console.ReadLine(); if (inputLine == "r") { Console.WriteLine("Perform Request (large single response)"); var resPacket = _clientConnector.SendRequest(1, 1, new GetListRequestPacket()) as GetListResponsePacket; //Console.WriteLine($"response packet:{JsonConvert.SerializeObject(resPacket)}"); Console.WriteLine($"response packet count:{resPacket.Records.Count}"); } else if (inputLine == "m") { Console.WriteLine("Perform Request - multi responses"); for (int i = 0; i < 10; i++) { _clientConnector.SendRequestMultiResponses( 1, 2, new GetListRequestPacket(), MultiResponseCallback); } //var resPacket = _clientConnector.SendRequest(1, 1, new GetListRequestPacket()) as GetListResponsePacket; //Console.WriteLine($"response packet:{JsonConvert.SerializeObject(resPacket)}"); //Console.WriteLine($"response packet count:{resPacket.List.Count}"); } else if (inputLine == "x") { Console.WriteLine("TestRequestMultiResponsesHandler"); var test = new TestRequestMultiResponsesHandler(); test.Run(); } else { Console.WriteLine("input incorrect."); } } catch (Exception ex) { Console.WriteLine("Exception:" + ex.ToString()); } } }
public void GetLogInfos(EServiceType serviceType, string date, string sellerAccount, string logLevel) { ClientConnector.GetLogInfos(serviceType, date, sellerAccount, logLevel); }