public TCPServer(IMessageProcessor processor, string ipAddress, int port) { this.processor = processor; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port); processor?.Process($"TCP server listening on {endPoint.ToString()}"); socket.Bind(endPoint); socket.Listen(ListenerCOunt); Socket acceptedSocket = socket.Accept(); byte[] acceptedData = new byte[acceptedSocket.SendBufferSize]; int bufferCount = acceptedSocket.Receive(acceptedData); byte[] data = new byte[bufferCount]; for (int i = 0; i < bufferCount; i++) { data[i] = acceptedData[i]; } string message = Encoding.Default.GetString(data); processor?.Process(message); }
public TCPServer(IMessageProcessor processor, string ipAddress, int port) { this.processor = processor; socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port); processor?.Process($"TCP Server listening on {endPoint.ToString()}"); socket.Bind(endPoint); socket.Listen(ListenerCount); }
public void Listen() { Socket acceptedSocket = socket.Accept(); byte[] recivedData = new byte[acceptedSocket.SendBufferSize]; while (true) { int bufferCount = acceptedSocket.Receive(recivedData); byte[] data = new byte[bufferCount]; for (int i = 0; i < bufferCount; i++) { data[i] = recivedData[i]; } string message = Encoding.Default.GetString(data); if (message.Equals("exit")) { Environment.Exit(0); } processor?.Process(message); } }
public void Listen() { Socket acceptedSocket = socket.Accept(); byte[] receiveData = new byte[acceptedSocket.SendBufferSize]; while (true) { int bufferSize = acceptedSocket.Receive(receiveData); byte[] data = new byte[bufferSize]; for (int i = 0; i < bufferSize; i++) { data[i] = receiveData[i]; } string message = Encoding.Default.GetString(data); processor?.Process(message); if (message == "exit") { break; } } }
public void Listen() { Socket acceptedAccept = socket.Accept(); do { byte[] acceptedData = new byte[acceptedAccept.SendBufferSize]; int bufferedCount = acceptedAccept.Receive(acceptedData); byte[] data = new byte[bufferedCount]; for (int i = 0; i < bufferedCount; i++) { data[i] = acceptedData[i]; } message = Encoding.Default.GetString(data); processor?.Process(message); } while (!message.ToUpper().Equals("Konec".ToUpper())); }
private void PollServer(TrackedService server) { bool pollOk = true; string commandArg = null; if (server.ServiceType == ServiceType.Block) { commandArg = "heartbeatB"; } else if (server.ServiceType == ServiceType.Root) { commandArg = "heartbeatR"; } else if (server.ServiceType == ServiceType.Manager) { commandArg = "heartbeatM"; } else { tracker.log.Error(String.Format("Don't know how to poll type {0}", server.ServiceType)); pollOk = false; } // Send the poll command to the server, IMessageProcessor p = connector.Connect(server.ServiceAddress, ServiceType.Block); MessageStream outputStream = new MessageStream(); outputStream.AddMessage(new Message("poll", commandArg)); IEnumerable <Message> inputStream = p.Process(outputStream); foreach (Message m in inputStream) { // Any error with the poll means no status change, if (m.HasError) { pollOk = false; } } // If the poll is ok, set the status of the server to UP and remove from // the monitor list, if (pollOk) { // The server status is set to 'STATUS_UP' if either the current state // is 'DOWN CLIENT REPORT' or 'DOWN HEARTBEAT' // Synchronize over 'servers_map' for safe alteration of the ref. ServiceStatus oldStatus; lock (monitoredServers) { oldStatus = server.CurrentStatus; if (oldStatus == ServiceStatus.DownClientReport || oldStatus == ServiceStatus.DownHeartbeat) { server.CurrentStatus = ServiceStatus.Up; } // Remove the server from the monitored_servers list. monitoredServers.Remove(server); } if (tracker.log.IsInterestedIn(LogLevel.Information)) { tracker.log.Info(String.Format("Poll ok. Status now UP for {0} {1}", server.ServiceAddress, server.ServiceType)); } // Fire the event if the status changed, try { if (tracker.StatusChange != null) { tracker.StatusChange(this, new ServiceStatusEventArgs(server.ServiceAddress, server.ServiceType, oldStatus, ServiceStatus.Up)); } } catch (Exception e) { // Catch any exception generated. Log it but don't terminate the // thread. tracker.log.Error("Exception in listener during poll", e); } } else { // Make sure the server status is set to 'DOWN HEARTBEAT' if the poll // failed, // Synchronize over 'servers_map' for safe alteration of the ref. lock (monitoredServers) { ServiceStatus sts = server.CurrentStatus; if (sts == ServiceStatus.Up || sts == ServiceStatus.DownClientReport) { server.CurrentStatus = ServiceStatus.DownHeartbeat; } } } }
private static async void ProcessReceive(TcpTransport serverTransport, FrameData frameData, IMessageProcessor messageProcessor) { byte[] responseExtention = null; byte[] responseContent = null; byte responseCode = 0; try { ResponseBase response = null; if (frameData.TitleBytes == null || frameData.TitleBytes.Length == 0) { response = new ErrorResponse((byte)ResponseCode.SERVICE_TITLE_ERROR); } if (messageProcessor == null) { response = new ErrorResponse((byte)ResponseCode.SERVICE_NOT_FOUND); } if (response == null) { if (NetworkSettings.ServerProcessMode == CommunicationMode.Sync) { var responseTask = messageProcessor.Process(frameData); responseTask.Wait(); response = responseTask.Result; } else { response = await messageProcessor.Process(frameData); } } responseExtention = response.HeaderExtentionBytes ?? FrameFormat.EmptyBytes; responseContent = response.ContentBytes ?? FrameFormat.EmptyBytes; responseCode = (byte)response.Code; } catch { responseExtention = FrameFormat.EmptyBytes; responseContent = FrameFormat.EmptyBytes; responseCode = (byte)ResponseCode.SERVER_INTERNAL_ERROR; } try { var messageByteCount = FrameFormat.ComputeFrameByteCount(responseExtention, FrameFormat.EmptyBytes, responseContent); var sendBuffer = serverTransport.SendBufferCache.Get(messageByteCount); FrameFormat.FillFrame(sendBuffer, responseExtention, FrameFormat.EmptyBytes, responseContent, responseCode, frameData.MessageId); //if (NetworkSettings.ServerTcpSendMode == TcpSendMode.Async) //{ // serverTransport.SendAsync(sendBuffer, messageByteCount); //} //else //{ serverTransport.Send(sendBuffer, messageByteCount); //} serverTransport.SendBufferCache.Cache(sendBuffer); } catch { serverTransport.Close(); } }
private void SendBlockToTask(object state) { SendBlockInfo info = (SendBlockInfo)state; // Connect to the destination service address, IMessageProcessor p = service.Connector.Connect(info.Destination, ServiceType.Block); int blockType = service.DiscoverBlockType(info.BlockId); if (blockType == -1) { return; } BlockData data = service.GetBlockData(info.BlockId, blockType); // If the data was not found, exit, if (!data.Exists) { return; } try { BlockContainer blockContainer = service.FetchBlockContainer(info.BlockId); // If the block was written to less than 6 minutes ago, we don't allow // the copy to happen, if (!service.IsKnownStaticBlock(blockContainer)) { // This will happen if this block server has not be notified // recently by the managers the maximum block id they are managing. service.Logger.Info(String.Format("Can't copy last block_id ( {0} ) on server, it's not a known static block.", info.BlockId)); return; } IEnumerable <Message> inputStream; Message ouputMessage; // If the file does exist, push it over, byte[] buf = new byte[16384]; int pos = 0; Stream fin = data.OpenRead(); while (true) { int read = fin.Read(buf, 0, buf.Length); // Exit if we reached the end of the file, if (read == 0) { break; } ouputMessage = new Message("sendBlockPart", info.BlockId, pos, blockType, buf, read); // Process the message, inputStream = p.Process(ouputMessage.AsStream()); // Get the input iterator, foreach (Message m in inputStream) { if (m.HasError) { service.Logger.Info(String.Format("'sendBlockPart' command error: {0}", m.ErrorMessage)); return; } } pos += read; } // Close, fin.Close(); // Send the 'complete' command, ouputMessage = new Message("sendBlockComplete", info.BlockId, blockType); // Process the message, inputStream = p.Process(ouputMessage.AsStream()); // Get the input iterator, foreach (Message m in inputStream) { if (m.HasError) { service.Logger.Info(String.Format("'sendBlockCommand' command error: {0}", m.ErrorMessage)); return; } } // Tell the manager server about this new block mapping, ouputMessage = new Message("internalAddBlockServerMapping", info.BlockId, new long[] { info.DestinationServerId }); service.Logger.Info(String.Format("Adding block_id->server mapping ({0} -> {1})", info.BlockId, info.DestinationServerId)); for (int n = 0; n < info.ManagerServers.Length; ++n) { // Process the message, IMessageProcessor mp = service.Connector.Connect(info.ManagerServers[n], ServiceType.Manager); inputStream = mp.Process(ouputMessage.AsStream()); // Get the input iterator, foreach (Message m in inputStream) { if (m.HasError) { service.Logger.Info(String.Format("'internalAddBlockServerMapping' command error: @ {0} - {1}", info.ManagerServers[n], m.ErrorMessage)); break; } } } } catch (IOException e) { service.Logger.Info(e); } }
public async Task <TwiMLResult> IncomingMessage([FromForm] SmsRequest incomingMessage) { var response = await _messageProcessor.Process(incomingMessage.Body); return(TwiML(new MessagingResponse().Message(response))); }
private void InspectNetwork() { // If cached, if (machine_profiles == null) { // The sorted list of all servers in the schema, IServiceAddress[] slist = ServiceAddresses; List <MachineProfile> machines = new List <MachineProfile>(); foreach (IServiceAddress server in slist) { MachineProfile machine_profile = new MachineProfile(server); // Request a report from the administration role on the machine, IMessageProcessor mp = connector.Connect(server, ServiceType.Admin); RequestMessage request = new RequestMessage("report"); Message response = mp.Process(request); if (response.HasError) { machine_profile.ErrorState = response.ErrorMessage; } else { // Get the message replies, string b = response.Arguments[0].ToString(); bool is_block = !b.Equals("block=no"); String m = response.Arguments[1].ToString(); bool is_manager = !m.Equals("manager=no"); string r = response.Arguments[2].ToString(); bool is_root = !r.Equals("root=no"); long used_mem = response.Arguments[3].ToInt64(); long total_mem = response.Arguments[4].ToInt64(); long used_disk = response.Arguments[5].ToInt64(); long total_disk = response.Arguments[6].ToInt64(); ServiceType type = new ServiceType(); if (is_block) { type |= ServiceType.Block; } if (is_manager) { type |= ServiceType.Manager; } if (is_root) { type |= ServiceType.Root; } // Populate the lists, machine_profile.ServiceType = type; machine_profile.MemoryUsed = used_mem; machine_profile.MemoryTotal = total_mem; machine_profile.StorageUsed = used_disk; machine_profile.StorageTotal = total_disk; } // Add the machine profile to the list machines.Add(machine_profile); } machine_profiles = machines; } }