public NacosConfigService(ILoggerFactory loggerFactory, IOptions <NacosSdkOptions> optionsAccs) { this._logger = loggerFactory.CreateLogger <NacosConfigService>(); this._namespace = optionsAccs.Value.Namespace; this._configFilterChainManager = new ConfigFilterChainManager(optionsAccs.Value); this._worker = new ClientWorker(_logger, _configFilterChainManager, optionsAccs.Value); }
private void Send() { Task.Factory.StartNew(() => _errorHandler.Handle(() => { switch (SelectedCommandClient) { case CommandClient.Time: ServerTime = (DateTime?)ClientWorker.Send(SelectedCommandClient); break; case CommandClient.Echo: ReceivedServerMessage = (string)ClientWorker.Send(SelectedCommandClient, SendServerMessage); break; case CommandClient.Upload: IsWorkingWithFile = true; ClientWorker.Send(SelectedCommandClient, PathToUploadFile); IsWorkingWithFile = false; break; case CommandClient.Download: IsWorkingWithFile = true; ClientWorker.Send(SelectedCommandClient, PathToDownloadFile); IsWorkingWithFile = false; break; } })); }
/// <summary> /// Loops on processing a client forever /// threadContext will be a TTransport instance /// </summary> /// <param name="threadContext"></param> private void Execute() { while (!stop) { Thread t = null; lock (clientLock) { bool goAhead = false; //don't dequeue if too many connections goAhead = (clientThreads.Count < maxThreads); goAhead = goAhead && (clientQueue.Count > 0); if (goAhead) { TTransport client = clientQueue.Dequeue(); ClientWorker worker = new ClientWorker(client, this); t = new Thread(new ThreadStart(worker.DoWork)); clientThreads.Add(t); } } if (t == null) { Thread.Sleep(100); } else { //start processing requests from client on new thread t.Start(); } } }
public void Stop () { if (thread != null) { threadWorker.ShouldStop = true; Console.Write ("[{0}] Stopping sniffer client for {1} gracefully...", parentServer.SourceEndPoint, client.Client.RemoteEndPoint); for (int i = 0; i < 10; i++) { if (threadWorker.IsStopped) break; Thread.Sleep (100); } if (!threadWorker.IsStopped) { Console.WriteLine ("Failed!"); Console.WriteLine ("[{0}] Stopping sniffer client for {1} forcefully...", parentServer.SourceEndPoint, client.Client.RemoteEndPoint); thread.Abort (); threadWorker.CleanUp (); } Console.WriteLine ("Done!"); // Clear references threadWorker = null; thread = null; } }
public void BeforeTest() { ServerWorker server = new ServerWorker(); ClientWorker client = new ClientWorker(); server.Start(); }
protected NetworkManagerBase(NetworkConfig networkConfig, EcdsaKeyPair keyPair, byte[] hubPrivateKey, int version, int minPeerVersion) { if (networkConfig.Peers is null) { throw new ArgumentNullException(); } _messageFactory = new MessageFactory(keyPair); LocalNode = new Node { Version = 0, Timestamp = (ulong)DateTimeOffset.UtcNow.ToUnixTimeSeconds(), PublicKey = keyPair.PublicKey, Nonce = (uint)new Random().Next(1 << 30), BlockHeight = 0, Agent = "Lachain-v0.0-dev" }; _hubConnector = new HubConnector( string.Join(",", networkConfig.BootstrapAddresses), hubPrivateKey, networkConfig.NetworkName ?? "devnet", version, minPeerVersion, networkConfig.NewChainId ?? throw new Exception("No newChainId in config"), networkConfig.HubMetricsPort ?? 7072, _messageFactory, networkConfig.HubLogLevel ); _hubConnector.OnMessage += _HandleMessage; _broadcaster = new ClientWorker(new byte[33], _messageFactory, _hubConnector); _broadcaster.Start(); }
public void Stop() { if (thread != null) { threadWorker.ShouldStop = true; Console.Write("[{0}] Stopping sniffer client for {1} gracefully...", parentServer.SourceEndPoint, client.Client.RemoteEndPoint); for (int i = 0; i < 10; i++) { if (threadWorker.IsStopped) { break; } Thread.Sleep(100); } if (!threadWorker.IsStopped) { Console.WriteLine("Failed!"); Console.WriteLine("[{0}] Stopping sniffer client for {1} forcefully...", parentServer.SourceEndPoint, client.Client.RemoteEndPoint); thread.Abort(); threadWorker.CleanUp(); } Console.WriteLine("Done!"); // Clear references threadWorker = null; thread = null; } }
/* The GetFriendList MessageHandler * It handles messages of UPDATE_FRIENDSHIP_REQ type. */ private static void UpdateFriendship(RMessage message, TcpClient connection) { Console.WriteLine("UpdateFriendship"); FriendshipData friendship = (FriendshipData)message.Data; RMessage replyMessageFormer, replyMessageLatter; if (friendship.Status) { FriendshipConnector.ConfirmFriendship(friendship); replyMessageFormer = new RMessage(MessageType.CONFIRM_FRIENDSHIP_REPLY, friendship.Latter); replyMessageLatter = new RMessage(MessageType.CONFIRM_FRIENDSHIP_REPLY, friendship.Former); UserConnector.UpdateUserRank(friendship.Latter, Ranking.ADD_FRIEND); UserConnector.UpdateUserRank(friendship.Former, Ranking.ADD_FRIEND); } else { FriendshipConnector.DeleteFriendship(friendship); replyMessageFormer = new RMessage(MessageType.DENY_FRIENDSHIP_REPLY, friendship.Latter); replyMessageLatter = new RMessage(MessageType.DENY_FRIENDSHIP_REPLY, friendship.Former); } ClientWorker formerWorker = ServerCore.GetWorkerById(friendship.Former); if (formerWorker != null) { formerWorker.SendMessage(replyMessageFormer); } ClientWorker latterWorker = ServerCore.GetWorkerById(friendship.Latter); if (latterWorker != null) { latterWorker.SendMessage(replyMessageLatter); } }
public NacosConfigService(ConfigParam config, IHttpClientFactory factory) { _namespace = config.Namespace; _http = new FastHttp(factory, config); _agent = new ServerHttpAgent(config, _http); _localConfigInfoProcessor = new LocalConfigInfoProcessor(config.LocalFileRoot); _worker = new ClientWorker(config, _agent, _configFilterChainManager, _localConfigInfoProcessor); }
static void Main(string[] args) { IClientWorker worker = new ClientWorker(); worker.Start(3002); Console.ReadKey(); }
private void Connect_Click(object sender, RoutedEventArgs e) { if (tbIP.Text != "" && tbPort.Text != "") { clientWorker = new ClientWorker(Convert.ToInt32(tbPort.Text), tbIP.Text); stream = clientWorker.Read(); Refresh_ScreenAsync(); } }
public CommunicationManager() { _worker = new ClientWorker(); _peers = new ConcurrentDictionary <IPEndPoint, Peer>(); GlobalReceiveSpeedWatcher = new SpeedWatcher(); GlobalSendSpeedWatcher = new SpeedWatcher(); _worker.QueueForever(CalculateSpeed, 500.Milliseconds()); _worker.Start(); }
private void HandleAsyncConnection(IAsyncResult result) { connectionWaitHandle.Set(); Socket listener = (Socket)result.AsyncState; Socket workerSocket = listener.EndAccept(result); var proxy = new ClientWorker(workerSocket, this.settings); proxy.StartRelay(); }
private void Connect() { Task.Factory.StartNew(() => { IsConnecting = true; ClientWorker = new ClientWorker(); ClientWorker.Client.MessageReceived += OnMessageReceived; ClientWorker.Client.ProgressChanged += OnProgressChanged; Connected = (bool)ClientWorker.Send(CommandClient.Connect, ServerIPEndPoint); IsConnecting = false; }); }
private void Disconnect() { Task.Factory.StartNew(() => { if ((bool)ClientWorker.Send(CommandClient.Close)) { Connected = false; ClientWorker.Client.MessageReceived -= OnMessageReceived; ClientWorker.Dispose(); ClientWorker = null; } }); }
/// <summary> /// Initializes a new instance of the <see cref="CommunicationManager"/> class. /// </summary> /// <example> /// var portNumber = 9876; /// var listener = new Listener(portNumber); /// var comunicationManager = new CommunicationManager(_listener); /// comunicationManager.PeerConnected += ChatOnMemberConnected; /// comunicationManager.ConnectionClosed += ChatOnMemberDisconnected; /// comunicationManager.ConnectionFailed += ChatOnMemberConnectionFailure; /// comunicationManager.PeerDataReceived += OnPeerDataReceived; /// /// listener.Start(); /// </example> /// <param name="listener">The incomming connections <see cref="Listener"/>.</param> public CommunicationManager(TcpListener listener) { _listener = listener; _worker = new ClientWorker(); _ioActor = new ConnectionIoActor(_worker, new BufferAllocator(new byte[1 << 16])); _peers = new ConcurrentDictionary <IPEndPoint, Peer>(); _globalReceiveSpeedWatcher = new SpeedWatcher(); _globalSendSpeedWatcher = new SpeedWatcher(); _worker.QueueForever(CalculateSpeed, 500.Milliseconds()); _worker.Start(); _listener.ConnectionRequested += NewPeerConnected; }
/* * On connection crash, makes the user offline */ private static void MakeUserOffline(TcpClient connection) { uint id = ServerCore.GetIdByConnection(connection); UserData user = UserConnector.UpdateUserState(id, false); List <UserData> friendList = UserConnector.GetFriendList(id); RMessage replyMessage = new RMessage(MessageType.CHANGE_USER_STATE_REPLY, user); foreach (UserData friend in friendList) { ClientWorker worker = ServerCore.GetWorkerById(friend.Id); if (worker != null) { ServerCore.GetWorkerById(friend.Id).SendMessage(replyMessage); } } }
/* The GetFriendList MessageHandler * It handles messages of ADD_FRIEND_REQ type. */ private static void AddFriend(RMessage message, TcpClient connection) { Console.WriteLine("AddFriend"); uint thisUserId = ServerCore.GetIdByConnection(connection); UserData friend = UserConnector.GetUser((String)message.Data); UserData thisUser = UserConnector.GetUser(thisUserId); if (friend == null) { return; } if (friend.Id == thisUserId) { return; } List <FriendshipData> friendships = FriendshipConnector.GetFriendshipList(thisUserId); foreach (FriendshipData friendshipIt in friendships) { if (friendshipIt.Former == friend.Id || friendshipIt.Latter == friend.Id) { return; } } FriendshipData friendship = new FriendshipData(thisUserId, friend.Id, false); FriendshipConnector.AddFriendship(friendship); ClientWorker formerWorker = ServerCore.GetWorkerById(friendship.Former); ClientWorker latterWorker = ServerCore.GetWorkerById(friendship.Latter); RMessage replyMessageFormer = new RMessage(MessageType.ADD_FRIEND_REPLY, friend); RMessage replyMessageLatter = new RMessage(MessageType.ADD_FRIEND_REPLY, thisUser); RMessage replyMessage = new RMessage(MessageType.ADD_FRIENDSHIP_REPLY, friendship); if (formerWorker != null) { formerWorker.SendMessage(replyMessageFormer); formerWorker.SendMessage(replyMessage); } if (latterWorker != null) { latterWorker.SendMessage(replyMessageLatter); latterWorker.SendMessage(replyMessage); } }
/* The GetFriendList MessageHandler * It handles messages of CHANGE_USER_STATE_REQUEST type. */ private static void ChangeUserState(RMessage message, TcpClient connection) { Console.WriteLine("ChangeUserState"); uint id = ServerCore.GetIdByConnection(connection); UserData user = UserConnector.UpdateUserState(id, (bool)message.Data); List <UserData> friendList = UserConnector.GetFriendList(id); RMessage replyMessage = new RMessage(MessageType.CHANGE_USER_STATE_REPLY, user); foreach (UserData friend in friendList) { ClientWorker worker = ServerCore.GetWorkerById(friend.Id); if (worker != null) { ServerCore.GetWorkerById(friend.Id).SendMessage(replyMessage); } } ServerCore.GetWorkerByConnection(connection).SendMessage(replyMessage); }
private ClientWorker?CreateMsgChannel(ECDSAPublicKey publicKey) { if (_messageFactory.GetPublicKey().Equals(publicKey)) { return(null); } if (_clientWorkers.TryGetValue(publicKey, out var existingWorker)) { return(existingWorker); } Logger.LogTrace($"Connecting to peer {publicKey.ToHex()}"); var worker = new ClientWorker(publicKey, _messageFactory, _hubConnector); _clientWorkers.Add(publicKey, worker); worker.Start(); return(worker); }
/// <summary> /// Start sniffing this client. /// </summary> public void Start () { if (thread == null) { Console.Write ("[{0}] Starting sniffer client for {1}...", parentServer.SourceEndPoint, client.Client.RemoteEndPoint); targetClient.Connect (parentServer.TargetEndPoint); threadWorker = new ClientWorker (this); thread = new Thread (threadWorker.DoWork); thread.Start (); // Wait until Thread is alive. while (!thread.IsAlive) Thread.Sleep (1); Console.WriteLine ("Done!"); } }
public void TcpModeStart() { tcp_alloction_mode_retry_counts++; if (tcp_alloction_mode_retry_counts > 3) { MessageBox.Show("tcp alloctaed prots didnt work."); ChangeMode(TypeOfMode.Dissconnected); return; } TcpUdpMode_Panel.Visible = true; UdpTcpStatus_Label.Text = "Connecting To Allocated Server Port"; ClientWorkerData client_worker_data = new ClientWorkerData(new MessageReceivedInform(MessageReceivedInform), new MainFormInvoke(this.Invoke) , send_to_worker_construct, receive_from_worker_construct, client_worker_pulse_object, client_worker_cancel_construct); client_worker_thread = new Thread(() => ClientWorker.WorkerMainThread(client_worker_data, server_tcp_ip_endpoint)); is_there_worker = true; client_worker_thread.Start(); }
/// <summary> /// Start sniffing this client. /// </summary> public void Start() { if (thread == null) { Console.Write("[{0}] Starting sniffer client for {1}...", parentServer.SourceEndPoint, client.Client.RemoteEndPoint); targetClient.Connect(parentServer.TargetEndPoint); threadWorker = new ClientWorker(this); thread = new Thread(threadWorker.DoWork); thread.Start(); // Wait until Thread is alive. while (!thread.IsAlive) { Thread.Sleep(1); } Console.WriteLine("Done!"); } }
private Action <IMessage> SendTo(ClientWorker peer) { return(x => { Logger.LogTrace($"Sending {x.GetType()} to {peer.PeerPublicKey.ToHex()}"); NetworkMessage msg = x switch { PingReply pingReply => new NetworkMessage { PingReply = pingReply }, SyncBlocksReply syncBlockReply => new NetworkMessage { SyncBlocksReply = syncBlockReply }, SyncPoolReply syncPoolReply => new NetworkMessage { SyncPoolReply = syncPoolReply }, GetPeersReply getPeersReply => new NetworkMessage { GetPeersReply = getPeersReply }, _ => throw new InvalidOperationException() }; peer.AddMsgToQueue(msg); }); }
/// <summary> /// Конструктор /// </summary> private Kernel() { Client = new ClientWorker("192.168.1.34", 4505); Client.ConnectAsync(); }
protected override Thread createWorker(TcpClient client) { Console.WriteLine("create worker"); worker = new ClientWorker(server, client); return(new Thread(new ThreadStart(worker.run))); }
protected override Thread CreateWorker(TcpClient client) { Worker = new ClientWorker(Server, client); return(new Thread(new ThreadStart(Worker.Run))); }
protected override Thread createWorker(TcpClient client) { worker = new ClientWorker(server, client); return(new Thread(new ThreadStart(worker.run))); }
public MessageEnvelope(ECDSAPublicKey publicKey, ClientWorker remotePeer) { PublicKey = publicKey; RemotePeer = remotePeer; }
/// <summary> /// Loops on processing a client forever /// threadContext will be a TTransport instance /// </summary> /// <param name="threadContext"></param> private void Execute() { while (!stop) { Thread t = null; lock (clientLock) { bool goAhead = false; //don't dequeue if too many connections goAhead = (clientThreads.Count < maxThreads); goAhead = goAhead && (clientQueue.Count > 0); if (goAhead) { TTransport client = clientQueue.Dequeue(); ClientWorker worker = new ClientWorker(client, this); t = new Thread(new ThreadStart(worker.DoWork)); clientThreads.Add(t); } } if (t == null) Thread.Sleep(100); else //start processing requests from client on new thread t.Start(); } }
protected override Thread createWorker(TcpClient client) { this._worker = new ClientWorker(_serverService, client); return(new Thread(new ThreadStart(_worker.Run))); }
public void Reconnect() { Client = new ClientWorker("127.0.0.1", 5432); }