private void DoClient(ConnectClient client) { try { if (LogMessage != null) { LogMessage("New connect"); } using (var ss = new SessionServer()) { ss.LogMessage += LogMessage; ss.Do(client); } } catch (Exception e) { var errorText = ExceptionUtil.ExceptionLog(e, "Server Exception"); if (!(e is SocketException) && !(e.InnerException is SocketException)) { if (LogMessage != null) { LogMessage(errorText); } } } //if (LogMessage != null) LogMessage("End connect"); Interlocked.Decrement(ref _ActiveClientCount); }
/// <summary> /// 断开一个连接 /// </summary> /// <param name="e">操作对象</param> private void CloseClientSocket(SocketAsyncEventArgs e) { if (e.LastOperation == SocketAsyncOperation.Receive) { ConnectClient conn = connectClient.FirstOrDefault(P => P.saea_receive == e); if (conn == null) { return; } try { conn.socket.Shutdown(SocketShutdown.Both); } // 抛出客户端进程已经关闭 catch (Exception) { } conn.socket.Close(); m_receivePool.Push(e); connectClient.TryTake(out conn); m_maxNumberAcceptedClients.Release(); if (OnClose != null) { OnClose(conn.connectId); } } else { } }
public void ReceiveConnect(ConnectClient message) { if (!IsConnected) { Connect?.Invoke(); } }
/// <summary> /// 当异步连接完成时调用此方法 /// </summary> /// <param name="e">操作对象</param> private void ProcessAccept(SocketAsyncEventArgs e) { connectId++; //把连接到的客户端信息添加到集合中 ConnectClient connecttoken = new ConnectClient(); connecttoken.socket = e.AcceptSocket; //从接受端重用池获取一个新的SocketAsyncEventArgs对象 connecttoken.saea_receive = m_receivePool.Pop(); connecttoken.saea_receive.UserToken = connectId; connecttoken.saea_receive.AcceptSocket = e.AcceptSocket; connectClient.TryAdd(connectId, connecttoken); clientList.TryAdd(connectId, e.AcceptSocket.RemoteEndPoint.ToString()); //一旦客户机连接,就准备接收。 if (!e.AcceptSocket.ReceiveAsync(connecttoken.saea_receive)) { ProcessReceive(connecttoken.saea_receive); } //事件回调 if (OnAccept != null) { OnAccept(connectId); } //接受第二连接的请求 StartAccept(e); }
public void SerializeAndDeSerializeConnectClientMessages() { ConnectClient connect = new ConnectClient(); byte[] bytes = Serializer.Serialize(connect, 0); ConnectClient message = (ConnectClient)Serializer.DeSerializeServer(bytes, 0); Assert.AreEqual(connect, message, "Should be able to serialize and deserialize the connect client message."); }
private void DoClient(ConnectClient client) { SessionServer session = null; string addrIP = ((IPEndPoint)client.Client.Client.RemoteEndPoint).Address.ToString(); try { try { if (Repository.CheckIsBanIP(addrIP)) { Loger.Log("Abort connect BanIP " + addrIP); } else { Loger.Log($"New connect {addrIP} (connects: {ActiveClientCount})"); session = new SessionServer(); lock (Sessions) { Sessions.Add(session); } session.Do(client, SessionsAction); } } catch (ObjectDisposedException) { Loger.Log("Abort connect Relogin " + addrIP); } catch (Transfer.ConnectClient.ConnectSilenceTimeOutException) { Loger.Log("Abort connect TimeOut " + addrIP); } catch (Exception e) { if (!(e is SocketException) && !(e.InnerException is SocketException) && !(e is Transfer.ConnectClient.ConnectNotConnectedException) && !(e.InnerException is Transfer.ConnectClient.ConnectNotConnectedException)) { ExceptionUtil.ExceptionLog(e, "Server Exception"); } } //if (LogMessage != null) LogMessage("End connect"); } finally { Interlocked.Decrement(ref _ActiveClientCount); Loger.Log($"Close connect {addrIP}{(session == null ? "" : " " + session?.GetNameWhoConnect())} (connects: {ActiveClientCount})"); try { if (session != null) { session.Dispose(); } } catch { } } }
private void Initialize() { ConnectClient = new ConnectClient(ref ClientGrid, ref MessagersGrid); TableUsers = ConnectClient.TableUsers(); FIOComboBox.DataSource = TableUsers; FIOComboBox.DisplayMember = "Name"; FIOComboBox.ValueMember = "UserID"; }
/// <summary> /// 客户端断开一个连接 /// </summary> /// <param name="connectId">连接标记</param> internal void Close(Guid connectId) { ConnectClient conn = connectClient.FirstOrDefault(P => P.connectId == connectId); if (conn == null) { return; } CloseClientSocket(conn.saea_receive); }
public void Do(ConnectClient client) { Client = client; Loger.Log("Server ReceiveBytes1"); ///установка условно защищенного соединения //Строго первый пакет: Передаем серверу КОткр var rc = Client.ReceiveBytes(); var crypto = new CryptoProvider(); if (SessionClient.UseCryptoKeys) { crypto.OpenKey = Encoding.UTF8.GetString(rc); } //Строго первый ответ: Передаем клиенту КОткр(Сессия) SetKey(); Loger.Log("Server SendMessage1"); if (SessionClient.UseCryptoKeys) { Client.SendMessage(crypto.Encrypt(Key)); } else { Client.SendMessage(Key); } //if (LogMessage != null) LogMessage("session Connected"); Worker = new Service(); ///рабочий цикл while (true) { //Loger.Log("Server Loop1"); var rec = Client.ReceiveBytes(); //Loger.Log("Server Loop2"); var rec2 = CryptoProvider.SymmetricDecrypt(rec, Key); //Loger.Log("Server " + Loger.Bytes(rec2)); //Loger.Log("Server Loop3"); var recObj = (ModelContainer)GZip.UnzipObjByte(rec2); //Deserialize //Loger.Log("Server Loop4"); var sendObj = Service(recObj); //Loger.Log("Server Loop5"); var ob = GZip.ZipObjByte(sendObj); //Serialize //Loger.Log("Server Loop6"); var send = CryptoProvider.SymmetricEncrypt(ob, Key); //Loger.Log("Server Loop7"); Client.SendMessage(send); } }
public void OnEnable() { if (main == null) { main = this; } else { Destroy(this); } }
/// <summary> /// 给连接对象设置附加数据 /// </summary> /// <param name="connectId">连接标识</param> /// <param name="data">附加数据</param> /// <returns>true:设置成功,false:设置失败</returns> internal bool SetAttached(Guid connectId, object data) { ConnectClient connect = connectClient.FirstOrDefault(P => P.connectId == connectId); if (connect == null) { return(false); } connect.attached = data; return(true); }
internal bool InitKKNet(Guid connectId) { ConnectClient connect = connectClient.FirstOrDefault(P => P.connectId == connectId); if (connect == null) { return(false); } connect.KKNet = new KKNetEngine.KKNet(); return(true); }
internal bool Decode(Guid connectId, byte[] data, int num) { ConnectClient connect = connectClient.FirstOrDefault(P => P.connectId == connectId); if (connect == null) { return(false); } connect.KKNet.Decode(data, num); return(true); }
private ISession GetSession(Uri serverUri, ICredentials credentials) { ISession session = null; _sessions.TryGetValue(serverUri + credentials.UserName, out session); if (session == null) { var connectClient = new ConnectClient(serverUri, new Clients.Credentials(credentials.UserName, credentials.Password)); session = new Session(connectClient); _sessions.TryAdd(serverUri + credentials.UserName, session); } return session; }
/// <summary> /// 获取连接对象的附加数据 /// </summary> /// <param name="connectId">连接标识</param> /// <returns>附加数据,如果没有找到则返回null</returns> internal T GetAttached <T>(Guid connectId) { ConnectClient connect = connectClient.FirstOrDefault(P => P.connectId == connectId); if (connect == null || connect.attached == null) { return(default(T)); } else { return((T)connect.attached); } }
private ISession GetSession(Uri serverUri, ICredentials credentials) { ISession session = null; _sessions.TryGetValue(serverUri + credentials.UserName, out session); if (session == null) { var connectClient = new ConnectClient(serverUri, new Clients.Credentials(credentials.UserName, credentials.Password)); session = new Session(connectClient); _sessions.TryAdd(serverUri + credentials.UserName, session); } return(session); }
public async Task GetAccessTokenAsync_WithValidTokenRequest_ReturnsAccessToken() { // Given: We fetch create a token request string authCode = "abcde"; // Set a valid access token here ConnectClient connectClient = new ConnectClient(this.ClientId, this.ClientSecret); TokenRequest tokenRequest = new TokenRequest(authCode, DefaultRedirectUrl); // When: We request the auth code TokenResponse tokenResponse = await connectClient.GetAccessTokenAsync(tokenRequest); // Then: The access token should not be null Assert.IsFalse(string.IsNullOrEmpty(tokenResponse.AccessToken)); }
public async Task RevokeAccessTokenAsync_WithValidToken_DoesNotThrowError() { // Given: We create a revoke token request string accessToken = "abcde"; ConnectClient connectClient = new ConnectClient(this.ClientId, this.ClientSecret); RevokeTokenRequest revokeTokenRequest = new RevokeTokenRequest() { TokenTypeHint = TokenType.AccessToken, Token = accessToken }; // When: we send the request await connectClient.RevokeTokenAsync(revokeTokenRequest); }
protected async ValueTask <IEnumerable <RestItem> > FindRelationAndFollowAsync(string relation, string errorHeading, StringBuilder loggingStringBuilder) { var stopwatch = new Stopwatch(); IEnumerable <RestItem> result = new List <RestItem>(); if (State != null) { var theUri = FindRelationUri(relation); loggingStringBuilder.AppendFormat("Call to url={0} ", theUri); stopwatch.Start(); IRestResponse <List <RestItem> > response = new RestResponse <List <RestItem> >(); int tryIterationCounter = 1; while (tryIterationCounter <= 3) { try { response = await ConnectClient.RequestAsync <List <RestItem> >(theUri, Method.GET); break; } catch (JsonSerializationException ex) { if (tryIterationCounter == 3) { Logger.LogWarning($"JsonSerializationException Method=FindRelationAndFollow {ex}"); return(null); } await Task.Delay(500); } catch (Exception ex) { throw ex; } tryIterationCounter++; } loggingStringBuilder.AppendFormat("took duration={0}ms - ", stopwatch.ElapsedMilliseconds); if (response.ErrorException != null) { RestErrorHelper.LogRestError(Logger, response, errorHeading); throw new Exception($"Error calling {theUri} - ", response.ErrorException); } result = response.Data; } stopwatch.Stop(); return(result); }
private void ConnectionAccepted(ConnectClient client) { if (ActiveClientCount > MaxActiveClientCount) { client.Dispose(); return; } Interlocked.Increment(ref _ActiveClientCount); ActiveClientCount++; var thread = new Thread(() => DoClient(client)); thread.IsBackground = true; thread.Start(); }
/// <summary> /// 接受处理回调 /// </summary> /// <param name="e">操作对象</param> private void ProcessReceive(SocketAsyncEventArgs e) { //检查远程主机是否关闭连接 if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { ConnectClient client = connectClient.FirstOrDefault(P => P.saea_receive == e); if (client == null) { return; } //如果接收到数据,超时记录设置为0 if (overtime > 0) { if (client != null) { client.keep_alive = 0; } } //回调 if (OnReceive != null) { if (client != null) { OnReceive(client.connectId, e.Buffer, e.Offset, e.BytesTransferred); } } //准备下次接收数据 try { if (!client.socket.ReceiveAsync(e)) { ProcessReceive(e); } } catch (ObjectDisposedException ex) { if (OnClose != null) { OnClose(client.connectId); } } } else { //Console.WriteLine($"断开----{e.GetHashCode()}"); CloseClientSocket(e); } }
public void GetAuthorizationUrl_WithMultipleScopes_GeneratesAuthorizationUrl() { // Given: We create a new connect client ConnectClient connectClient = new ConnectClient(this.ClientId, this.ClientSecret); // When: We get the authorization URL string authorizationUrl = connectClient.GetAuthorizationUrl("abcdef", new List <string>() { AppPermissions.PaymentsRead, AppPermissions.PaymentsWrite }); // Then: string expectedUrl = $"https://www.mollie.com/oauth2/authorize?client_id={this.ClientId}&state=abcdef&scope=payments.read+payments.write&response_type=code&approval_prompt=auto"; Assert.AreEqual(expectedUrl, authorizationUrl); }
private async Task <IEnumerable <RestItem> > GetRootAsync() { var stopwatch = new Stopwatch(); var messageStringBuilder = new StringBuilder("GetRoot request..."); try { stopwatch.Start(); var getRootResponse = await ConnectClient.LoginAsync(); messageStringBuilder.AppendFormat("took {0}ms", stopwatch.ElapsedMilliseconds); stopwatch.Restart(); if (getRootResponse.ErrorException != null || getRootResponse.Content == null) { RestErrorHelper.LogRestError(Logger, getRootResponse, "GetRoot HTTP error"); throw new Exception("Error calling GetRoot", getRootResponse.ErrorException); } if (getRootResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new NotAuthenticatedException("Username or password are incorrect"); } if (getRootResponse.Content != null) { return(getRootResponse.Content.FromJson <List <RestItem> >()); } } catch (NotAuthenticatedException) { throw; } catch (Exception ex) { Logger.LogError("GetRoot exception", ex); throw; } finally { Logger.LogError(messageStringBuilder.ToString()); stopwatch.Stop(); } return(null); }
public ISession GetSession(Uri serverUri, ICredentials credentials) { if (_sessions.TryGetValue(serverUri + credentials.UserName, out ISession session)) { return(session); } else { var connectClient = new ConnectClient(LoggerFactory.CreateLogger <ConnectClient>(), serverUri, new Clients.Credentials(credentials.UserName, credentials.Password)); var newSession = new Session(connectClient, LoggerFactory.CreateLogger <Session>(), Cache); if (_sessions.TryAdd(serverUri + credentials.UserName, newSession)) { return(newSession); } } return(default);
/// <summary> /// 超时机制 /// </summary> private void Heartbeat() { //计算超时次数 ,超过count就当客户端断开连接。服务端清除该连接资源 int count = overtime / overtimecheck; while (true) { ConnectClient client = connectClient.FirstOrDefault(P => P.keep_alive >= count); if (client != null) { client.keep_alive = 0; CloseClientSocket(client.saea_receive); } foreach (var item in connectClient) { item.keep_alive++; } Thread.Sleep(overtimecheck * 1000); } }
private void ProcessAccept(SocketAsyncEventArgs e) { connectId++; ConnectClient connecttoken = new ConnectClient(); connecttoken.socket = e.AcceptSocket; connecttoken.saea_receive = m_receivePool.Pop(); connecttoken.saea_receive.UserToken = connectId; connecttoken.saea_receive.AcceptSocket = e.AcceptSocket; connectClient.TryAdd(connectId, connecttoken); clientList.TryAdd(connectId, e.AcceptSocket.RemoteEndPoint.ToString()); if (!e.AcceptSocket.ReceiveAsync(connecttoken.saea_receive)) { ProcessReceive(connecttoken.saea_receive); } if (OnAccept != null) { OnAccept(connectId); } StartAccept(e); }
private static void Main(string[] args) { ConnectClient.Initialize(cfg => { cfg.WithDefaultNationSlug("YOUR_TEST_NATION_SLUG"); cfg.WithDefaultCredentials(new SimpleApiTokenCredentials("YOUR_API_TOKEN")); // OR //cfg.WithDefaultCredentials(new OAuthCredentials("YOUR_OAUTH_TOKEN")); }); var listSamples = new ListServiceSamples(); var peopleSamples = new PeopleServiceSamples(); var exportToolsSamples = new ExportToolsSamples(); // WARNING - Do not run these on a production nation. // These samples will modify data //listSamples.Run(); //peopleSamples.Run(); //exportToolsSamples.ExportListAsHouseholds(21); //exportToolsSamples.ExportListAsPeople(21); }
/// <summary> /// 当异步连接完成时调用此方法 /// </summary> /// <param name="e">操作对象</param> private void ProcessAccept(SocketAsyncEventArgs e) { //把连接到的客户端信息添加到集合中 ConnectClient connecttoken = new ConnectClient(); connecttoken.connectId = Guid.NewGuid(); connecttoken.socket = e.AcceptSocket; //从接受端重用池获取一个新的SocketAsyncEventArgs对象 connecttoken.saea_receive = m_receivePool.Pop(); connectClient.Add(connecttoken); //一旦客户机连接,就准备接收。 if (!e.AcceptSocket.ReceiveAsync(connecttoken.saea_receive)) { ProcessReceive(connecttoken.saea_receive); } //事件回调 if (OnAccept != null) { OnAccept(connecttoken.connectId); } //接受第二连接的请求 StartAccept(e); }
protected string FindRelationAndFollowAsString(string relation, string errorHeading, StringBuilder loggingStringBuilder) { var stopwatch = new Stopwatch(); var result = string.Empty; if (State != null) { var theUri = FindRelationUri(relation); loggingStringBuilder.AppendFormat("Beginning call to url={0} ", theUri); stopwatch.Start(); var response = ConnectClient.Request(theUri, Method.GET); loggingStringBuilder.AppendFormat("took duration={0}ms", stopwatch.ElapsedMilliseconds); if (response.ErrorException != null || response.Content == null) { RestErrorHelper.LogRestError(Logger, response, errorHeading); throw new Exception(string.Format("Error calling {0}", theUri), response.ErrorException); } result = response.Content; } stopwatch.Stop(); return(result); }
public void SendEcho() { if (string.IsNullOrEmpty(_virtualHost)) { throw new Exception("virtualHost is not defined"); } var link = State.Links.First(restLink => restLink.Relation == "http://api.sportingsolutions.com/rels/stream/batchecho"); var echouri = new Uri(link.Href); var streamEcho = new StreamEcho { Host = _virtualHost, Message = Guid.NewGuid() + ";" + DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") }; var response = ConnectClient.Request(echouri, RestSharp.Method.POST, streamEcho, UDAPI.Configuration.ContentType, 3000); if (response.ErrorException != null || response.Content == null) { RestErrorHelper.LogRestError(Logger, response, "Error sending echo request"); throw new Exception(string.Format("Error calling {0}", echouri), response.ErrorException); } }
/// <summary> /// 异步发送消息 /// </summary> /// <param name="sendQuere">发送消息体</param> private void Send(SendingQueue sendQuere) { ConnectClient client = connectClient.FirstOrDefault(P => P.connectId == sendQuere.connectId); if (client == null || client.socket.Connected == false) { return; } //如果发送池为空时,临时新建一个放入池中 mutex.WaitOne(); if (m_sendPool.Count == 0) { SocketAsyncEventArgs saea_send = new SocketAsyncEventArgs(); saea_send.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed); m_sendPool.Push(saea_send); } SocketAsyncEventArgs sendEventArgs = m_sendPool.Pop(); mutex.ReleaseMutex(); sendEventArgs.UserToken = client.connectId; sendEventArgs.SetBuffer(sendQuere.data, sendQuere.offset, sendQuere.length); try { if (!client.socket.SendAsync(sendEventArgs)) { ProcessSend(sendEventArgs); } } catch (ObjectDisposedException ex) { if (OnClose != null) { OnClose(client.connectId); } } }
public WhenPushingBatchEventWithError() { _testHandler = new CaptureHttpHandler(@"{""test"": [ {""success"": false, ""message"": ""Error"" }]}"); _connect = TestConfigurator.GetTestableClient(_testHandler); }
public WhenAddingBatchEvent() { _rootFolderName = Guid.NewGuid().ToString(); _testHandler = new CaptureHttpHandler(); _connect = TestConfigurator.GetTestableClient(_testHandler, _rootFolderName); }
public WhenPushingPendingEvents() { _rootFolderName = Guid.NewGuid().ToString(); _testHandler = new CaptureHttpHandler(@"{""WhenPushingStoredEvents"": [ {""success"": true }]}"); _connect = TestConfigurator.GetTestableClient(_testHandler, _rootFolderName); }
public WhenPushingSingleUnprocessableEvent() { var responseText = @"{""errors"": [ { ""field"":""Hello"", ""description"":""Invalid Greeting"" } ]}"; _testHandler = new CaptureHttpHandler(responseText, (HttpStatusCode)422); _connect = TestConfigurator.GetTestableClient(_testHandler); }
public WhenPushingSingleSuccessfullEvent() { _testHandler = new CaptureHttpHandler(); _connect = TestConfigurator.GetTestableClient(_testHandler); }
public WhenPushingAnEventWithReservedProperties() { _testHandler = new CaptureHttpHandler(); _connect = TestConfigurator.GetTestableClient(_testHandler); }
public WhenPushingSuccessfullBatchEvent() { _testHandler = new CaptureHttpHandler(@"{""test"": [ {""success"": true }]}"); _connect = TestConfigurator.GetTestableClient(_testHandler); }
public WhenPushingSingleDuplicateEvent() { var responseText = @"{""errorMessage"": ""Error""}"; _testHandler = new CaptureHttpHandler(responseText, HttpStatusCode.Conflict); _connect = TestConfigurator.GetTestableClient(_testHandler); }