public void RequestReply() { ThreadPool.QueueUserWorkItem(state => { var server = new ResponseSocket(); server.Bind("tcp://*:5555"); while (!_stopLoops) { try { var receiveFrame = server.ReceiveFrameBytes(); var request = Serializer.Deserialize <Request>(new MemoryStream(receiveFrame)); var response = OnRequest(request); using (var responseStream = new MemoryStream()) { Serializer.Serialize(responseStream, response); server.SendFrame(responseStream.ToArray()); } } catch (Exception e) { Console.WriteLine(e); } } }); }
private void EventLoop() { var addr = context.ConnectionInfo.HeartbeatZmqAddress; this.logger.LogDebug("Starting heartbeat server at {Address}.", addr); socket = new ResponseSocket(); socket.Bind(addr); while (alive) { // We use the Bytes receiver so that we can ping back data // unmodified, without worrying about encodings. try { var data = socket.ReceiveFrameBytes(); logger.LogDebug($"Got heartbeat message of length {data.Length}."); if (!socket.TrySendFrame(data)) { logger.LogError("Error sending heartbeat message back to client."); } } catch (ThreadInterruptedException) { continue; } catch (Exception ex) { logger.LogCritical(ex, "Unhandled exception in heartbeat loop."); } } }
public void StartRsp(int port) { using (var server = new ResponseSocket("@tcp://localhost:5556"))// bind { byte[] m1 = server.ReceiveFrameBytes(); Console.WriteLine("From Client: {0}", m1); // server.SendFrame // Send a response back from the server server.SendFrame("Hi Back"); } }
static void Main(string[] args) { using (var server = new ResponseSocket()) { server.Bind("tcp://*:5555"); while (true) { var data = server.ReceiveFrameBytes(); Console.WriteLine($"Received {data.Length} bytes"); server.SendFrame(new byte[1]); } } }
private void StartServerLoop(object state) { _socket.Bind(_address); while (!_stopEvent.Wait(0)) { byte[] data = _socket.ReceiveFrameBytes(); _logger.LogInformation(System.Text.Encoding.Default.GetString(data)); // Echoing back whatever was received _socket.TrySendFrame(data); } }
private static void StartHeartbeatLoop(string heartbeatAddress) { HeartbeatSocket.Bind(heartbeatAddress); while (!StopEvent.Wait(0)) { var data = HeartbeatSocket.ReceiveFrameBytes(); Log.Info(Encoding.Default.GetString(data)); // Echoing back whatever was received HeartbeatSocket.TrySendFrame(data); } }
public void HeartBeat() { using (_heartbeat = new ResponseSocket(_heartbeatEndpoint)) { while (!_cancel.IsCancellationRequested) { var heartbeatQuery = _heartbeat.ReceiveFrameBytes() .Deserialize <Heartbeat>(); _heartbeat.SendFrame(Heartbeat.Response.Serialize()); } } }
public void Respond(Func <TextRequest, TextResponse> callback) { var server = new ResponseSocket(); server.Bind(Address.OriginalString); while (true) { var bRequest = server.ReceiveFrameBytes(); var sRequest = Encoding.Unicode.GetString(bRequest); var sReturn = callback(new TextRequest(sRequest)); var bReturn = Encoding.Unicode.GetBytes(sReturn.Text); server.SendFrame(bReturn); } }
public void Start(string address) { using (ResponseSocket responseSocket = new ResponseSocket("@tcp://" + address)) { while (true) { byte[] buf = responseSocket.ReceiveFrameBytes(); TCPUserToken tCPUserToken = new TCPUserToken { Data = buf, Socket = responseSocket }; queue.Add(tCPUserToken); } } }
public void HandleHeartbeat() { using (_heartbeatSocket = new ResponseSocket(_configuration.HeartbeatEndpoint)) { while (!_cancel.IsCancellationRequested) { var messageBytes = _heartbeatSocket.ReceiveFrameBytes(); if (_cancel.IsCancellationRequested) { return; } _heartbeatSocket.SendFrame(_serializer.Serialize(Heartbeat.Response)); } } }
public async Task StartAsync(CancellationToken cancellationToken) { await Task.Yield(); _server.Bind(_address); using (Logger <Heartbeat> .Log.OnEnterAndExit()) { while (!cancellationToken.IsCancellationRequested) { var data = _server.ReceiveFrameBytes(); // Echoing back whatever was received _server.TrySendFrame(data); } } }
private static void ListenForSocketRequests() { _socketServer = new ResponseSocket(Ipc.RepoZIpcEndpoint.Address); while (true) { bool hasMore; var load = _socketServer.ReceiveFrameBytes(out hasMore); string message = Encoding.UTF8.GetString(load); if (string.IsNullOrEmpty(message)) { return; } if (message.StartsWith("list:", StringComparison.Ordinal)) { string repositoryNamePattern = message.Substring("list:".Length); string answer = "(no repositories found)"; try { var aggregator = TinyIoCContainer.Current.Resolve <IRepositoryInformationAggregator>(); var repos = aggregator.Repositories .Where(r => string.IsNullOrEmpty(repositoryNamePattern) || Regex.IsMatch(r.Name, repositoryNamePattern, RegexOptions.IgnoreCase)) .Select(r => $"{r.Name}|{r.BranchWithStatus}|{r.Path}") .ToArray(); if (repos.Any()) { answer = string.Join(Environment.NewLine, repos); } } catch (Exception ex) { answer = ex.Message; } _socketServer.SendFrame(Encoding.UTF8.GetBytes(answer)); } Thread.Sleep(100); } }
public void HandleHeartbeat() { using (_heartbeat = new ResponseSocket(_brokerConfiguration.HeartbeatEndpoint)) { while (!_cancel.IsCancellationRequested) { var heartbeatQuery = _heartbeat.ReceiveFrameBytes() .Deserialize <Heartbeat>(); if (_cancel.IsCancellationRequested) { return; } _heartbeat.SendFrame(Heartbeat.Response.Serialize()); } } }
static void Main(string[] args) { using (var commandreceiver = new ResponseSocket("@tcp://*:5555")) { while (true) { var msg = commandreceiver.ReceiveFrameBytes(); using (var stream = new MemoryStream(msg)) { CreateAccount command = Serializer.Deserialize <CreateAccount>(stream); //Serializer.Deserialize<string>(stream); Console.WriteLine("id = " + command.AccountId + " holder name = " + command.HolderName); commandreceiver.SendFrame(new AccountCreated(new Guid(), "test").ToString()); //return } } } }
public Task StartAsync(CancellationToken cancellationToken) { _server.Bind(_address); Task.Run(() => { using (Logger <Heartbeat> .Log.OnEnterAndExit()) { while (!cancellationToken.IsCancellationRequested) { var data = _server.ReceiveFrameBytes(); // Echoing back whatever was received _server.TrySendFrame(data); } } }, cancellationToken); return(Task.CompletedTask); }
public void Start() { using (_heartbeat = new ResponseSocket(_endpoint)) { while (!_cancel.IsCancellationRequested) { var messageBytes = _heartbeat.ReceiveFrameBytes(); var message = JsonConvert.DeserializeObject <HeartbeatQuery>(Encoding.UTF8.GetString(messageBytes)); var response = new HeartbeatResponse() { Endpoint = _endpoint }; var responseBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response)); _heartbeat.SendFrame(responseBytes); } } }
public void Start(CancellationToken cancellationToken) { using (_activeResponder = new ResponseSocket()) { // Bind _activeResponder.Bind(_activeEndPoint); _running = true; while (_running && !cancellationToken.IsCancellationRequested) { try { // Receive byte[] request = _activeResponder.ReceiveFrameBytes(); MessageFrame <THeader, TPayload> messageFrame = MessageSerializer.Deserialize <MessageFrame <THeader, TPayload> >(request); if (ReceiveMessage != null) { MessageFrame <THeader, TPayload> reply = ReceiveMessage(messageFrame.MessageType, messageFrame.Payload); // Do some work Thread.Sleep(1); // Send _activeResponder.SendFrame(MessageSerializer.ObjectToByteArray(reply), false); } } catch (Exception) { if (_running) { throw; } } } } _activeResponder = null; }
public void HandleHeartbeat() { using (_heartbeat = new ResponseSocket(_configuration.HeartbeatEndpoint)) { while (!_cancel.IsCancellationRequested) { var heartbeatQuery = _heartbeat.ReceiveFrameBytes() .Deserialize <Heartbeat>(); if (heartbeatQuery.Descriptor.ActorType == ActorType.Worker) { if (_registeredWorkers.TryGetValue(heartbeatQuery.Descriptor.ActorId, out var worker)) { worker.LastHeartbeat = DateTime.Now; } } _heartbeat.SendFrame(this.GetHeartbeat(HeartbeatType.Pong).Serialize()); } } }
public static async Task <int> Main(string[] args) { if (args.Length != 1) { await Console.Error.WriteLineAsync("Please specify the server name!"); return(1); } string serverName = args[0]; using (ResponseSocket server = new ResponseSocket()) { await Console.Out.WriteLineAsync($"Starting server '{serverName}'"); Message message = new Message(); message.Name = serverName; server.Bind("tcp://localhost:5556"); while (true) { byte[] reply = server.ReceiveFrameBytes(); Message replyMsg = Message.Parser.ParseFrom(reply); await Console.Out.WriteLineAsync($"{replyMsg.ShowString()}"); message.Timestamp = DateTime.UtcNow.Ticks; message.Body = "thank you"; await Console.Out.WriteLineAsync($"{message.ShowString()}"); byte[] serverMsg = message.ToByteArray(); server.SendFrame(serverMsg); //Thread.Sleep(5000); } } }
private static void Main() { Console.Title = "NetMQ LazyPirate Server"; const string serverEndpoint = "tcp://127.0.0.1:5555"; var random = new Random(); using (var server = new ResponseSocket()) { Console.WriteLine("S: Binding address {0}", serverEndpoint); server.Bind(serverEndpoint); var cycles = 0; while (true) { byte[] request = server.ReceiveFrameBytes(); cycles++; if (cycles > 3 && random.Next(0, 10) == 0) { Console.WriteLine("S: Simulating a crash"); Thread.Sleep(5000); } else if (cycles > 3 && random.Next(0, 10) == 0) { Console.WriteLine("S: Simulating CPU overload"); Thread.Sleep(1000); } Console.WriteLine("S: Normal request ({0})", Encoding.Unicode.GetString(request)); server.SendFrame(request); } } }
public byte[] Recv_Byte() { return(socket.ReceiveFrameBytes()); }
public void TryRunning() { try { RefreshOpenTasks(); using (var responseSocket = new ResponseSocket()) { _logger.Info("Started the server", _threadId); responseSocket.Bind(_settings.ServerIP); DateTime lastRefresh = DateTime.Now; while (_settings.ContinueRunning) { if (AutomaticRefresh && (DateTime.Now - lastRefresh).TotalMinutes > 3 && OpenTasks.Count < 500) { lastRefresh = DateTime.Now; RefreshOpenTasks(); } try { _logger.Info("Waiting for frame", _threadId); var requestBytes = responseSocket.ReceiveFrameBytes(); if (!_settings.ContinueRunning) { _logger.Info("don't continue received, quitting server...", _threadId); return; } string prettySize = AutomationUtili.MakePrettySize(requestBytes.Length); _logger.Info("received a byte[] with a length of " + prettySize, _threadId); MessageFromClientToServer req; try { req = LZ4MessagePackSerializer.Deserialize <MessageFromClientToServer>(requestBytes); } catch (Exception ex) { _logger.Exception(ex, "failed to deserialize string with " + requestBytes.Length + " bytes", _threadId); AnswerRequest(responseSocket, new MessageFromServerToClient(ServerResponseEnum.NothingToDo, Guid.NewGuid().ToString())); continue; } _logger.Info("Received: " + req.ClientName + ": " + req.ClientRequest + " ## ", _threadId); MessageFromServerToClient answer; // ReSharper disable once SwitchStatementMissingSomeCases _clients.TrackLastRequest(req); switch (req.ClientRequest) { case ClientRequestEnum.RequestForJob: answer = HandleRequestForJob(req); break; case ClientRequestEnum.ReportFinish: answer = HandleTaskFinishReport(req); break; case ClientRequestEnum.ReportFailure: answer = HandleFailureReport(req); break; case ClientRequestEnum.RequestForLPGFiles: answer = HandleRequestForLpgFiles(req); break; case ClientRequestEnum.ReportDiskspaceFull: answer = HandleDiskFullReport(req); break; default: _logger.Error("Invalid client request: " + req.ClientRequest, _threadId); AnswerRequest(responseSocket, new MessageFromServerToClient(ServerResponseEnum.NothingToDo, "no idea what you want")); throw new DistSimException("Invalid request"); } _logger.Info("Sent: " + req.ClientName + ": " + answer.ServerResponse, _threadId); AnswerRequest(responseSocket, answer); _clients.TrackLastAnswer(req.ClientName, answer); } catch (Exception ex) { ThreadException = ex; _logger.Exception(ex, "Exception in the server thread inner loop: \n" + ex.StackTrace); throw; } } } } catch (Exception ex) { ThreadException = ex; _logger.Exception(ex, "Exception in the server thread: \n"); throw; } }