internal void Start() { isStart = true; Task.Run(() => { while (isStart) { if (RunningTasks.Count < MaxTaskCount) { DataInfo commandinfo; if (commandInfos.TryDequeue(out commandinfo)) { Task task = new Task(() => { var command = DbHelper.Current.Get <PoolCommand>(DataType.CommandType, commandinfo.ID); HeartbeatCommand.UpdateHeartTime(commandinfo.State); PoolJob.TcpServer.ReceivedCommandAction(commandinfo.State, command); }); task.ContinueWith(t => { RunningTasks.Remove(task); }); RunningTasks.Add(task); task.Start(); } } } }); }
public virtual void heartbeatTriggered(IChannelHandlerContext ctx) { int? heartbeatTimes = (int?)ctx.Channel.GetAttribute(Connection.HEARTBEAT_COUNT).Get(); Connection conn = ctx.Channel.GetAttribute(Connection.CONNECTION).Get(); if (heartbeatTimes >= maxCount) { try { conn.close(); logger.LogError("Heartbeat failed for {} times, close the connection from client side: {} ", heartbeatTimes, ((IPEndPoint)ctx.Channel?.RemoteAddress)?.ToString()); } catch (System.Exception e) { logger.LogWarning("Exception caught when closing connection in SharableHandler.", e); } } else { bool?heartbeatSwitch = (bool?)ctx.Channel.GetAttribute(Connection.HEARTBEAT_SWITCH).Get(); if (!heartbeatSwitch.HasValue || !heartbeatSwitch.Value) { return; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final rpc.HeartbeatCommand heartbeat = new rpc.HeartbeatCommand(); HeartbeatCommand heartbeat = new HeartbeatCommand(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final InvokeFuture future = new rpc.DefaultInvokeFuture(heartbeat.getId(), new InvokeCallbackListener() InvokeFuture future = new DefaultInvokeFuture(heartbeat.Id, new InvokeCallbackListenerAnonymousInnerClass(this, ctx, heartbeat), null, heartbeat.ProtocolCode.FirstByte, commandFactory); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int heartbeatId = heartbeat.getId(); int heartbeatId = heartbeat.Id; conn.addInvokeFuture(future); if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Send heartbeat, successive count={}, Id={}, to remoteAddr={}", heartbeatTimes, heartbeatId, ctx.Channel.RemoteAddress.ToString()); } var writeFlushTask = ctx.WriteAndFlushAsync(heartbeat); writeFlushTask.ContinueWith((task) => { if (task.IsCompletedSuccessfully) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Send heartbeat done! Id={}, to remoteAddr={}", heartbeatId, ctx.Channel.RemoteAddress.ToString()); } } else { logger.LogError("Send heartbeat failed! Id={}, to remoteAddr={}", heartbeatId, ctx.Channel.RemoteAddress.ToString()); } }); //.addListener(new ChannelFutureListenerAnonymousInnerClass(this, ctx, future, heartbeatId)); TimerHolder.Timer.NewTimeout(new TimerTaskAnonymousInnerClass(this, conn, future, heartbeatId), TimeSpan.FromMilliseconds(heartbeatTimeoutMillis)); } }
private void ParseCommand(string commandText) { if (DebuggingHook != null) { DebuggingHook(commandText); return; } //_log.Debug("[Card Command parsing ] step 1"); commandText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + commandText; // _log.Debug("[Card command parsing] before load"); //_log.Debug(commandText); var doc = new XmlDocument(); doc.LoadXml(commandText); if (HeartbeatCommand.TryParseNExecute(doc)) { return; } TappingCardCommand tappingCardCommand; if (TappingCardCommand.TryParse(doc, out tappingCardCommand)) { ProgramIdleChecker.StubActivity(); if (!FrmScanning.SingleInstance.UpdateMsgWorker.Busy()) { FrmScanning.SingleInstance.UpdateMsgWorker.RunAsync(); } tappingCardCommand.Execute(); return; } AfterdebitCommand afterdebitCommand; if (AfterdebitCommand.TryParse(doc, out afterdebitCommand)) { ProgramIdleChecker.StubActivity(); afterdebitCommand.Execute(); return; } _log.Error("########Fatal Error#########"); throw new Exception("Unexpected command received:" + commandText); }
/// <summary> /// 心跳包 查好友 查排行 发送 /// </summary> void Refresh_Send() { if (isLogin) { if (Time.time - lastTime >= heartBeatTime) { HeartbeatCommand.Heartbeat_Send();//心跳包发送 if (MMunePanel.Get()) { RankCommand.Rank_Send(); //获取查询排行的命令 SelectFriendCommand.SelectFriendList(); //查找所有好友 } if (RoomsHallPanel.Get()) { RoomCommand.SelectRooms();//获取所有房间 } //if (RoomPanel.Get()) //{ // RoomCommand.RefreshThisRoomInfo(myInfo.roomNum);//刷新当前房间信息 //} lastTime = Time.time; } } }
public void HeartbeatCommandTest() { var heartbeatCommand = new HeartbeatCommand(); Assert.IsTrue(heartbeatCommand.IsValid); }
private void processReceivedDataQueue() { while (isStarted) { if (this.receivedDataQueue.Count > 0) { var item = receivedDataQueue.Dequeue(); Task.Run(() => { var state = item.Key; var buffer = item.Value; var commandDataList = new List <byte[]>(); var index = 0; List <byte> bytes = null; while (index < buffer.Length) { if (bytes == null) { if ((index + 3) < buffer.Length && buffer[index] == PoolCommand.DefaultPrefixBytes[0] && buffer[index + 1] == PoolCommand.DefaultPrefixBytes[1] && buffer[index + 2] == PoolCommand.DefaultPrefixBytes[2] && buffer[index + 3] == PoolCommand.DefaultPrefixBytes[3]) { bytes = new List <byte>(); bytes.AddRange(PoolCommand.DefaultPrefixBytes); index += 4; } else { index++; } } else { if ((index + 3) < buffer.Length && buffer[index] == PoolCommand.DefaultSuffixBytes[0] && buffer[index + 1] == PoolCommand.DefaultSuffixBytes[1] && buffer[index + 2] == PoolCommand.DefaultSuffixBytes[2] && buffer[index + 3] == PoolCommand.DefaultSuffixBytes[3]) { bytes.AddRange(PoolCommand.DefaultSuffixBytes); commandDataList.Add(bytes.ToArray()); bytes = null; index += 4; } else { bytes.Add(buffer[index]); index++; } } } if (this.ReceivedCommandAction != null) { foreach (var data in commandDataList) { try { var cmd = PoolCommand.ConvertBytesToMessage(data); if (cmd != null) { HeartbeatCommand.UpdateHeartTime(state); this.ReceivedCommandAction(state, cmd); } } catch (Exception ex) { LogHelper.Error("Error occured on deserialize messgae: " + ex.Message, ex); } } } }); } } }
private void processReceive(IAsyncResult ar) { TcpReceiveState state = (TcpReceiveState)ar.AsyncState; try { //if (state.Stream == null || !state.Stream.CanRead) //{ // state.Buffer = new byte[m_receiveBufferSize]; // state.Stream.BeginRead(state.Buffer, 0, state.Buffer.Length, new AsyncCallback(processReceive), state); //} int numberOfBytesRead = state.Stream.EndRead(ar); if (numberOfBytesRead > 0) { //LogHelper.Debug($"Readed {numberOfBytesRead} byte data from {state.Address}"); var buffer = new byte[numberOfBytesRead]; Array.Copy(state.Buffer, 0, buffer, 0, buffer.Length); //this.receivedDataQueue.Enqueue(new KeyValuePair<TcpReceiveState, byte[]>(state, buffer)); var commandDataList = new List <byte[]>(); var index = 0; List <byte> bytes = null; while (index < buffer.Length) { if (bytes == null) { if ((index + 3) < buffer.Length && buffer[index] == PoolCommand.DefaultPrefixBytes[0] && buffer[index + 1] == PoolCommand.DefaultPrefixBytes[1] && buffer[index + 2] == PoolCommand.DefaultPrefixBytes[2] && buffer[index + 3] == PoolCommand.DefaultPrefixBytes[3]) { bytes = new List <byte>(); bytes.AddRange(PoolCommand.DefaultPrefixBytes); index += 4; } else { index++; } } else { if ((index + 3) < buffer.Length && buffer[index] == PoolCommand.DefaultSuffixBytes[0] && buffer[index + 1] == PoolCommand.DefaultSuffixBytes[1] && buffer[index + 2] == PoolCommand.DefaultSuffixBytes[2] && buffer[index + 3] == PoolCommand.DefaultSuffixBytes[3]) { bytes.AddRange(PoolCommand.DefaultSuffixBytes); commandDataList.Add(bytes.ToArray()); bytes = null; index += 4; } else { bytes.Add(buffer[index]); index++; } } } if (this.ReceivedCommandAction != null) { foreach (var data in commandDataList) { try { var cmd = PoolCommand.ConvertBytesToMessage(data); if (cmd != null) { HeartbeatCommand.UpdateHeartTime(state); this.ReceivedCommandAction(state, cmd); } } catch (Exception ex) { LogHelper.Error("Error occured on deserialize messgae: " + ex.Message, ex); } } } } state.Buffer = new byte[m_receiveBufferSize]; state.Stream.BeginRead(state.Buffer, 0, state.Buffer.Length, new AsyncCallback(processReceive), state); } catch (Exception ex) { LogHelper.Error("Error occured on receive messgae: " + ex.Message, ex); this.CloseSocket(state); } }
/// <seealso cref= CommandDecoder#decode(io.netty.channel.IChannelHandlerContext, io.netty.buffer.IByteBuffer, java.util.List<object>) </seealso> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void decode(io.netty.channel.IChannelHandlerContext ctx, io.netty.buffer.IByteBuffer in, java.util.List<object><Object> out) throws Exception public virtual void decode(IChannelHandlerContext ctx, IByteBuffer @in, List <object> @out) { // the less length between response header and request header if (@in.ReadableBytes >= lessLen) { @in.MarkReaderIndex(); byte protocol = @in.ReadByte(); @in.ResetReaderIndex(); if (protocol == RpcProtocol.PROTOCOL_CODE) { /* * ver: version for protocol * type: request/response/request oneway * cmdcode: code for remoting command * ver2:version for remoting command * requestId: id of request * codec: code for codec * (req)timeout: request timeout * (resp)respStatus: response status * classLen: length of request or response class name * headerLen: length of header * contentLen: length of content * className * header * content */ if (@in.ReadableBytes > 2) { @in.MarkReaderIndex(); @in.ReadByte(); //version byte type = @in.ReadByte(); //type if (type == RpcCommandType.REQUEST || type == RpcCommandType.REQUEST_ONEWAY) { //decode request if (@in.ReadableBytes >= RpcProtocol.RequestHeaderLength - 2) { short cmdCode = @in.ReadShort(); byte ver2 = @in.ReadByte(); int requestId = @in.ReadInt(); byte serializer = @in.ReadByte(); int timeout = @in.ReadInt(); short classLen = @in.ReadShort(); short headerLen = @in.ReadShort(); int contentLen = @in.ReadInt(); byte[] clazz = null; byte[] header = null; byte[] content = null; if (@in.ReadableBytes >= classLen + headerLen + contentLen) { if (classLen > 0) { clazz = new byte[classLen]; @in.ReadBytes(clazz); } if (headerLen > 0) { header = new byte[headerLen]; @in.ReadBytes(header); } if (contentLen > 0) { content = new byte[contentLen]; @in.ReadBytes(content); } } else { // not enough data @in.ResetReaderIndex(); return; } RequestCommand command; if (cmdCode == (short)CommonCommandCode.__Enum.HEARTBEAT) { command = new HeartbeatCommand(); } else { command = createRequestCommand(cmdCode); } command.Type = type; command.Version = ver2; command.Id = requestId; command.Serializer = serializer; command.Timeout = timeout; command.Clazz = clazz; command.Header = header; command.Content = content; @out.Add(command); } else { @in.ResetReaderIndex(); } } else if (type == RpcCommandType.RESPONSE) { //decode response if (@in.ReadableBytes >= RpcProtocol.ResponseHeaderLength - 2) { short cmdCode = @in.ReadShort(); byte ver2 = @in.ReadByte(); int requestId = @in.ReadInt(); byte serializer = @in.ReadByte(); short status = @in.ReadShort(); short classLen = @in.ReadShort(); short headerLen = @in.ReadShort(); int contentLen = @in.ReadInt(); byte[] clazz = null; byte[] header = null; byte[] content = null; if (@in.ReadableBytes >= classLen + headerLen + contentLen) { if (classLen > 0) { clazz = new byte[classLen]; @in.ReadBytes(clazz); } if (headerLen > 0) { header = new byte[headerLen]; @in.ReadBytes(header); } if (contentLen > 0) { content = new byte[contentLen]; @in.ReadBytes(content); } } else { // not enough data @in.ResetReaderIndex(); return; } ResponseCommand command; if (cmdCode == (short)CommonCommandCode.__Enum.HEARTBEAT) { command = new HeartbeatAckCommand(); } else { command = createResponseCommand(cmdCode); } command.Type = type; command.Version = ver2; command.Id = requestId; command.Serializer = serializer; command.ResponseStatus = (ResponseStatus)status; command.Clazz = clazz; command.Header = header; command.Content = content; command.ResponseTimeMillis = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds(); command.ResponseHost = (IPEndPoint)ctx.Channel.RemoteAddress; @out.Add(command); } else { @in.ResetReaderIndex(); } } else { string emsg = "Unknown command type: " + type; logger.LogError(emsg); throw new Exception(emsg); } } } else { string emsg = "Unknown protocol: " + protocol; logger.LogError(emsg); throw new Exception(emsg); } } }
public InvokeCallbackListenerAnonymousInnerClass(RpcHeartbeatTrigger outerInstance, IChannelHandlerContext ctx, HeartbeatCommand heartbeat) { this.outerInstance = outerInstance; this.ctx = ctx; this.heartbeat = heartbeat; }