├── .gitignore ├── META-INF └── MANIFEST.MF ├── README.md ├── logs ├── error.log.2018-08-20 ├── error.log.2018-08-27 ├── error.log.2018-08-30 ├── error.log.2018-08-31 ├── gameExecutorEvent.log.2018-07-20 ├── gameExecutorEvent.log.2018-07-21 ├── gameExecutorEvent.log.2018-07-23 ├── gameExecutorEvent.log.2018-08-15 ├── gameExecutorEvent.log.2018-08-16 ├── gameExecutorEvent.log.2018-08-17 └── server_status ├── pom.xml ├── proto └── protoc-3.2.10-win32.改成zip就行 └── src ├── main ├── assembly │ └── assembly.xml ├── java │ ├── META-INF │ │ └── MANIFEST.MF │ └── com │ │ └── twjitm │ │ └── core │ │ ├── bootstrap │ │ ├── AbstractNettyGameBootstrapService.java │ │ ├── Bootstrap.java │ │ ├── INettyBootstrapService.java │ │ ├── http │ │ │ ├── AbstractNettyGameBootstrapHttpService.java │ │ │ └── NettyGameBootstrapHttpService.java │ │ ├── info.java │ │ ├── rpc │ │ │ └── NettyGameBootstrapRpcService.java │ │ ├── tcp │ │ │ ├── AbstractNettyGameBootstrapTcpService.java │ │ │ └── NettyGameBootstrapTcpService.java │ │ └── udp │ │ │ ├── AbstractNettyGameBootstrapUdpService.java │ │ │ └── NettyGameBootstrapUdpService.java │ │ ├── common │ │ ├── annotation │ │ │ ├── MessageCommandAnnotation.java │ │ │ └── NettyRpcServiceAnnotation.java │ │ ├── check │ │ │ └── NettyLifeCycleCheckService.java │ │ ├── config │ │ │ ├── global │ │ │ │ ├── GameWebSocketConfig.java │ │ │ │ ├── GlobalConstants.java │ │ │ │ ├── KafkaConfig.java │ │ │ │ ├── NettyGameConfig.java │ │ │ │ ├── NettyGameHttpConfig.java │ │ │ │ ├── NettyGameRpcConfig.java │ │ │ │ ├── NettyGameServiceConfig.java │ │ │ │ ├── NettyGameServiceConfigService.java │ │ │ │ ├── NettyGameUdpConfig.java │ │ │ │ └── ZookeeperConfig.java │ │ │ └── rpc │ │ │ │ ├── RpcServerConfig.java │ │ │ │ └── RpcSystemConfig.java │ │ ├── entity │ │ │ ├── IMessage.java │ │ │ ├── chat │ │ │ │ ├── BoradCastAllChatMessage.java │ │ │ │ ├── ChatMessage.java │ │ │ │ ├── DeleteChatMessage.java │ │ │ │ ├── GroupChatMessage.java │ │ │ │ ├── ResponseErrorMessage.java │ │ │ │ └── ResponseMessage.java │ │ │ └── online │ │ │ │ ├── LoginOnlineClientTcpMessage.java │ │ │ │ ├── OnlineHeartClientHttpMessage.java │ │ │ │ ├── OnlineMessageUdpMessage.java │ │ │ │ ├── OnlineUserBroadCastMessage.java │ │ │ │ └── OnlineUserPo.java │ │ ├── enums │ │ │ ├── MessageAttributeEnum.java │ │ │ ├── MessageComm.java │ │ │ ├── MessageType.java │ │ │ └── NettyGameTypeEnum.java │ │ ├── factory │ │ │ ├── INettyTcpMessageFactory.java │ │ │ ├── MessageRegistryFactory.java │ │ │ ├── NettyRpcMethodRegistryFactory.java │ │ │ ├── NettyRpcRequestFactory.java │ │ │ ├── NettyTcpMessageFactory.java │ │ │ ├── classload │ │ │ │ ├── DynamicGameClassLoader.java │ │ │ │ ├── FileClassLoader.java │ │ │ │ └── NettyClassloader.java │ │ │ └── thread │ │ │ │ ├── NettyRpcHandlerThreadPoolFactory.java │ │ │ │ └── async │ │ │ │ ├── AsyncCall.java │ │ │ │ └── poll │ │ │ │ ├── AsyncThreadPool.java │ │ │ │ └── AsyncThreadService.java │ │ ├── handler │ │ │ ├── http │ │ │ │ ├── AbstractNettyNetMessageHttpServerHandler.java │ │ │ │ ├── HttpRequestHandler.java │ │ │ │ └── NettyNetMessageHttpServerHandler.java │ │ │ ├── infor.java │ │ │ ├── rpc │ │ │ │ ├── NettyNetRPCServerHandler.java │ │ │ │ └── NettyRpcClientServerHandler.java │ │ │ ├── socket │ │ │ │ └── NettyCommonSessionWebSocketHandler.java │ │ │ ├── tcp │ │ │ │ ├── AbstractNettyNetMessageTcpServerHandler.java │ │ │ │ ├── NettyNetLoggingHandler.java │ │ │ │ └── NettyNetMessageTcpServerHandler.java │ │ │ └── udp │ │ │ │ ├── AbstractNettyNetMessageUdpServerHandler.java │ │ │ │ └── NettyNetMessageUdpServerHandler.java │ │ ├── kafka │ │ │ ├── AbstractKafkaPushTask.java │ │ │ ├── KafkaTaskType.java │ │ │ ├── NettyKafkaConsumerListener.java │ │ │ └── NettyKafkaProducerListener.java │ │ ├── listener │ │ │ └── StartupServerListener.java │ │ ├── logic │ │ │ ├── chat │ │ │ │ ├── ChatHandler.java │ │ │ │ └── Impl │ │ │ │ │ └── ChatHandlerImpl.java │ │ │ ├── handler │ │ │ │ ├── AbstractBaseHandler.java │ │ │ │ └── BaseHandler.java │ │ │ └── online │ │ │ │ ├── Impl │ │ │ │ └── LoginOnLineHandlerImpl.java │ │ │ │ └── LoginOnLineHandler.java │ │ ├── netstack │ │ │ ├── builder │ │ │ │ ├── ISessionBuilder.java │ │ │ │ ├── NettyTcpSessionBuilder.java │ │ │ │ └── NettyUdpSessionBuilder.java │ │ │ ├── coder │ │ │ │ ├── decode │ │ │ │ │ ├── INettyNetProtoBuffToMessageDecoderFactory.java │ │ │ │ │ ├── http │ │ │ │ │ │ ├── INettyNetProtoBuffHttpToMessageDecoderFactory.java │ │ │ │ │ │ └── NettyNetProtoBuffHttpToMessageDecoderFactory.java │ │ │ │ │ ├── rpc │ │ │ │ │ │ └── NettyNetMessageRPCDecoder.java │ │ │ │ │ ├── tcp │ │ │ │ │ │ ├── INettyNetProtoBuffTCPToMessageDecoderFactory.java │ │ │ │ │ │ ├── NettyNetProtoBufMessageTCPDecoder.java │ │ │ │ │ │ └── NettyNetProtoBuffTCPToMessageDecoderFactory.java │ │ │ │ │ └── udp │ │ │ │ │ │ ├── INettyNetProtoBuffUDPToMessageDecoderFactory.java │ │ │ │ │ │ ├── NettyNetProtoBufMessageUDPDecoder.java │ │ │ │ │ │ └── NettyNetProtoBuffUDPToMessageDecoderFactory.java │ │ │ │ └── encode │ │ │ │ │ ├── INettyNetProtoBufMessageEncoderFactory.java │ │ │ │ │ ├── http │ │ │ │ │ ├── INettyNetProtoBufHttpMessageEncoderFactory.java │ │ │ │ │ └── NettyNetProtoBufHttpMessageEncoderFactory.java │ │ │ │ │ ├── rpc │ │ │ │ │ └── NettyNetMessageRPCEncoder.java │ │ │ │ │ ├── tcp │ │ │ │ │ ├── INettyNetProtoBufTcpMessageEncoderFactory.java │ │ │ │ │ ├── NettyNetProtoBufMessageTCPEncoder.java │ │ │ │ │ └── NettyNetProtoBufTcpMessageEncoderFactory.java │ │ │ │ │ └── udp │ │ │ │ │ ├── INettyNetProtoBufUdpMessageEncoderFactory.java │ │ │ │ │ ├── NettyNetProtoBufMessageUDPEncoder.java │ │ │ │ │ └── NettyNetProtoBufUdpMessageEncoderFactory.java │ │ │ ├── entity │ │ │ │ ├── AbstractNettyNetMessage.java │ │ │ │ ├── AbstractNettyNetProtoBufMessage.java │ │ │ │ ├── INettyMessage.java │ │ │ │ ├── NettyNetMessageBody.java │ │ │ │ ├── NettyNetMessageHead.java │ │ │ │ ├── NettyNetProtoBufMessageBody.java │ │ │ │ ├── http │ │ │ │ │ ├── AbstractNettyNetProtoBufHttpMessage.java │ │ │ │ │ └── NettyNetHttpMessageHead.java │ │ │ │ ├── rpc │ │ │ │ │ ├── NettyRpcRequestMessage.java │ │ │ │ │ └── NettyRpcResponseMessage.java │ │ │ │ ├── tcp │ │ │ │ │ ├── AbstractNettyNetProtoBufTcpMessage.java │ │ │ │ │ ├── NettyTCPMessageBody.java │ │ │ │ │ └── NettyTCPMessageHead.java │ │ │ │ └── udp │ │ │ │ │ ├── AbstractNettyNetProtoBufUdpMessage.java │ │ │ │ │ ├── NettyUDPMessageHead.java │ │ │ │ │ └── NettyUDpMessageBody.java │ │ │ ├── pipeline │ │ │ │ ├── INettyServerPipeLine.java │ │ │ │ ├── NettyTcpServerPipeLineImpl.java │ │ │ │ └── NettyUdpServerPipeLineImpl.java │ │ │ ├── sender │ │ │ │ ├── INetMessageSender.java │ │ │ │ ├── NettyNetTcpMessageSender.java │ │ │ │ └── NettyNetUdpMessageSender.java │ │ │ └── session │ │ │ │ ├── ISession.java │ │ │ │ ├── NettySession.java │ │ │ │ ├── tcp │ │ │ │ └── NettyTcpSession.java │ │ │ │ └── udp │ │ │ │ └── NettyUdpSession.java │ │ ├── process │ │ │ ├── IMessageProcessor.java │ │ │ ├── NettyNetMessageProcessLogic.java │ │ │ ├── NettyQueueMessageExecutorProcessor.java │ │ │ ├── tcp │ │ │ │ ├── INettyTcpNetProtoMessageProcess.java │ │ │ │ ├── ITcpMessageProcessor.java │ │ │ │ ├── NettyTcpMessageQueueExecutorProcessor.java │ │ │ │ └── NettyTcpNetProtoMessageProcess.java │ │ │ └── udp │ │ │ │ ├── NettyUdpNetProtoMessageProcessor.java │ │ │ │ └── NettyUdpOrderNetProtoMessageProcessor.java │ │ ├── proto │ │ │ ├── BaseMessageProto.java │ │ │ ├── LoginOnlineClientTcpMessagebuf.java │ │ │ ├── OnlineClientUdpMessageBuf.java │ │ │ └── OnlineHeratClientHttpMessageBuf.java │ │ ├── service │ │ │ ├── ILongId.java │ │ │ ├── INettyChannleOperationService.java │ │ │ ├── INettyLongFindService.java │ │ │ ├── IService.java │ │ │ ├── Impl │ │ │ │ ├── AbstractNettyGamePlayerFindService.java │ │ │ │ ├── NettyChannelOperationServiceImpl.java │ │ │ │ ├── NettyGamePlayerFindServiceImpl.java │ │ │ │ └── NettyGameServiceConfigServiceImpl.java │ │ │ ├── http │ │ │ │ └── AsyncNettyHttpHandlerService.java │ │ │ └── rpc │ │ │ │ ├── client │ │ │ │ ├── AbstractNettyRpcConnectManager.java │ │ │ │ ├── NettyAsyncRPCCallback.java │ │ │ │ ├── NettyRpcContextHolder.java │ │ │ │ ├── NettyRpcContextHolderObject.java │ │ │ │ ├── NettyRpcFuture.java │ │ │ │ └── proxy │ │ │ │ │ ├── INettyAsyncRpcProxy.java │ │ │ │ │ ├── NettyAsyncRpcProxy.java │ │ │ │ │ └── NettyObjectProxy.java │ │ │ │ ├── manager │ │ │ │ ├── NettyDbRpcConnectManager.java │ │ │ │ ├── NettyGameRpcConnectManager.java │ │ │ │ └── NettyWorldRpcConnectManager.java │ │ │ │ ├── network │ │ │ │ ├── NettyRpcClient.java │ │ │ │ ├── NettyRpcClientConnection.java │ │ │ │ └── NettyRpcServerConnectTask.java │ │ │ │ ├── serialize │ │ │ │ ├── INettyJsonSerializer.java │ │ │ │ ├── INettyRpcSerialize.java │ │ │ │ └── NettyProtoBufRpcSerialize.java │ │ │ │ ├── server │ │ │ │ ├── NettyRpcNodeInfo.java │ │ │ │ ├── NettySdRpcServiceProvider.java │ │ │ │ └── NettySdServer.java │ │ │ │ └── service │ │ │ │ ├── NettyRPCFutureService.java │ │ │ │ ├── NettyRemoteRpcHandlerService.java │ │ │ │ ├── NettyRpcClientConnectService.java │ │ │ │ └── NettyRpcProxyService.java │ │ ├── system │ │ │ ├── System.java │ │ │ └── SystemService.java │ │ ├── update │ │ │ ├── IUpdatable.java │ │ │ └── UpdateService.java │ │ ├── utils │ │ │ └── PackageScaner.java │ │ └── zookeeper │ │ │ ├── NettyZookeeperNodeInfo.java │ │ │ ├── NettyZookeeperNodeNettyGameTypeEnum.java │ │ │ ├── NettyZookeeperRpcServiceDiscoveryService.java │ │ │ └── NettyZookeeperRpcServiceRegistryService.java │ │ ├── initalizer │ │ ├── NettyHttpMessageServerInitializer.java │ │ ├── NettyRpcClientMessageServerInitializer.java │ │ ├── NettyRpcMessageServerInitializer.java │ │ ├── NettyTcpMessageServerInitializer.java │ │ ├── NettyUdpMessageServerInitializer.java │ │ └── NettyWebSocketServerInitializer.java │ │ ├── player │ │ ├── dao │ │ │ └── PlayerDao.java │ │ └── entity │ │ │ ├── GameNettyPlayer.java │ │ │ └── IGameNettyPlayer.java │ │ ├── service │ │ ├── dispatcher │ │ │ ├── IDispatcherService.java │ │ │ └── Impl │ │ │ │ └── DispatcherServiceImpl.java │ │ ├── rpc │ │ │ ├── infor.java │ │ │ └── service │ │ │ │ ├── HelloWorldImpl.java │ │ │ │ └── IHelloWorld.java │ │ └── user │ │ │ ├── Impl │ │ │ └── UserServiceImpl.java │ │ │ └── UserService.java │ │ ├── spring │ │ ├── SpringLoadServiceImpl.java │ │ └── SpringServiceManager.java │ │ ├── test │ │ ├── AsyncExecutorService.java │ │ ├── TestJson.java │ │ ├── TestServiceHandler.java │ │ └── TestWorldChatService.java │ │ ├── utils │ │ ├── file │ │ │ └── FileUtil.java │ │ ├── logs │ │ │ └── LoggerUtils.java │ │ ├── spring │ │ │ └── BeanUtils.java │ │ ├── time │ │ │ ├── TimeUtils.java │ │ │ └── timer │ │ │ │ ├── ExpirationListener.java │ │ │ │ ├── PollTimer.java │ │ │ │ └── TimeSlot.java │ │ ├── uuid │ │ │ ├── AtomicLimitNumber.java │ │ │ └── LongIdGenerator.java │ │ └── xml │ │ │ └── JdomUtils.java │ │ └── zookeeper │ │ ├── Constant.java │ │ └── ServiceRegistry.java └── resources │ ├── bean │ ├── game-kafka.properties │ ├── game-properties.properties │ ├── game-zookeeper.properties │ ├── log4j2-config.xml │ ├── netty-http-config.xml │ ├── netty-rpc-config.xml │ ├── netty-udp-config.xml │ ├── netty-websocket-config.xml │ ├── rpc-server-register.xml │ └── rpc-service-register.xml │ ├── log4j.properties │ ├── mail │ └── mail.properties │ ├── proto │ ├── LoginOnlineClientTcpMessagebuf.proto │ ├── OnlineClientUdpMessageBuf.proto │ ├── OnlineHeratClientHttpMessageBuf.proto │ └── build.sh │ └── spring │ ├── applicationContext-async-task.xml │ ├── applicationContext-kafka-producer.xml │ ├── applicationContext-kafka.consumer.xml │ ├── applicationContext-spring.xml │ └── applicationContext.xml └── test └── java └── com └── twjitm ├── ClientServiceTest.java ├── TestChannelInitializer.java ├── TestClientHandler.java ├── TestSpring.java ├── books ├── client │ ├── EchoClient.java │ └── EchoClientHandler.java └── server │ ├── EchoServer.java │ └── EchoServiceHandler.java ├── email ├── MailMessage.java ├── MailServer.java └── User.java ├── http ├── GameHttpClient.java ├── GameHttpClientHandler.java └── GameHttpClientInitializer.java ├── kafka ├── TestKafka.java └── WordChatTask.java ├── rpc ├── HelloWorldCallbackTest.java ├── HelloWorldServiceTest.java └── zookeeper │ └── NettyZookeeperTest.java ├── rts └── LobbySever.java ├── server └── TestServiceHandler.java ├── test ├── TestHashMap.java └── User.java ├── thread └── Test.java ├── threads ├── InputThreadTest.java └── ThreadTest.java └── udp └── ClientServiceUdpTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | *.zip 18 | *.tar.gz 19 | *.rar 20 | 21 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 22 | hs_err_pid* 23 | 24 | .idea/ 25 | target/ 26 | *.ini 27 | *.iml 28 | *.class 29 | # Created by https://www.gitignore.io/api/maven 30 | 31 | ### Maven ### 32 | target/ 33 | pom.xml.tag 34 | pom.xml.releaseBackup 35 | pom.xml.versionsBackup 36 | pom.xml.next 37 | release.properties 38 | dependency-reduced-pom.xml 39 | buildNumber.properties 40 | .mvn/timing.properties 41 | 42 | # Avoid ignoring Maven wrapper jar file (.jar files are usually ignored) 43 | !/.mvn/wrapper/maven-wrapper.jar 44 | 45 | 46 | # End of https://www.gitignore.io/api/maven 47 | 48 | 49 | *.class 50 | 51 | # Log file 52 | *.log 53 | 54 | # BlueJ files 55 | *.ctxt 56 | 57 | # Mobile Tools for Java (J2ME) 58 | .mtj.tmp/ 59 | 60 | # Package Files # 61 | *.jar 62 | *.war 63 | *.ear 64 | *.zip 65 | *.tar.gz 66 | *.rar -------------------------------------------------------------------------------- /META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Main-Class: com.twjitm.core.bootstrap.Bootstrap 3 | 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # twjitm-core 2 | ### 相关业务介绍 3 | 4 | ### Netty网络基础架构系统 5 | 6 | 采用Netty信息加载实现长连接实时通讯系统,客户端可以值任何场景,支持实时http通讯、webSocket通讯、tcp协议通讯、和udp协议通讯、广播协议等 7 | 通过http协议,rpc协议。 8 | 采用自定义网络数据包结构, 9 | 实现自定义网络栈。 10 | 11 | 1:支持分布式zookeeper进行服务节点配置。\ 12 | 2:采用自定义注解形式实现netty私有消息协议栈。\ 13 | 3:支持远程RPC调用。\ 14 | 4:支持redis。\ 15 | 5:支持db分离。\ 16 | 6: 支持同步和异步消息处理\ 17 | 7: 支持kafka消息队列提供/消费 模式来实现分布式消息队列\ 18 | 8: 支持数据加密传输,保障数据安全。\ 19 | 9: 支持分布式事务3pc提交,异常回滚。 20 | 21 | # 主要使用业务场景 22 | 23 | 1:游戏服务器\ 24 | 2:实时通讯系统\ 25 | 3:金融数据处理系统\ 26 | 4:对网络实时性要求较高的系统\ 27 | 5:常见互联网系统 28 | 29 | ### 目前在更新阶段 30 | 31 | 独立数据db模块,独立事务模块,独立线程调度模块。以微服务的形式提供网络服务。 32 | 33 | 34 | ### TCP 通信模式 35 | 36 | tcp通讯,采用netty实现tcp通讯,项目中可以利用 com\twjitm\core\start\GameService ,将启动模式改为tcp服务器启动模式 37 | 可以利用test中的\test\java\com\twjitm\ClientServiceTest 可以模拟客户端进行连接,需要将端口和地址改为tcp服务器进行连接。 38 | tcp消息处理采用消息队列,将所有到来的消息放到队列中,通过线程池化技术来处理消息。 39 | 40 | ### UDP 通信模式 41 | UDP自定义网络协议栈和tcp自定义网络协议栈格式差不多,不同的是udp不需要建立连接,也就是无状态的通信模式,在消息处理模块采用 42 | tcp连接的时候保存的session来确定是哪个客户端发出的消息,似的udp协议能够正确的处理,通过两种不同的消息处理模式,进行选择处理 43 | 其中有:同步队列模式;生产者-消费者模式。 44 | 45 | ### HTTP 通信模式 46 | HTTP协议同样采用自定义网络协议栈实现,和tcp,udp协议差不多,只不过数据包不一样,http是建立在tcp的应用层上的协议。 47 | 采用同步处理方式,当消息到来的时候及时作出处理。 48 | 49 | 50 | ### RPC 通信模式 51 | RPC模块分为同步调用和异步调用,远程服务器调用,利用netty实现轻量级rpc服务器框架,通过自定义线程让步策略。结合动态代理等 52 | java搞基知识,实现rpc服务器通讯模块。利用xml文档配置rpc服务器基本信息,以达到动态的水平扩展服务器。为分布式服务器做好 53 | 基础准备 54 | 55 | ### zookeeper 服务 56 | 57 | 通过整合zookeeper,动态的注册服务,发现服务,整合rpc逻辑,实现分布式服务发现和注册。 58 | 59 | ### kafka服务 60 | 61 | 通过整合kafka服务。实现分布式服务器消息队列,解耦系统中的逻辑。 62 | 63 | 64 | ### 其他 65 | 还在优化,优化项目中的空间复杂度,时间复杂度,相应时间,压测能力等性能 66 | 67 | ### spring容器的使用 68 | 69 | 本项目利用spring来统一管理一些bean,利用服务器启动的时候,统一将容器初始化提交给spring,利用spring提供的注解,轻松获得 70 | 注入到spring容器中的bean对象,提高代码的可读性。 71 | 72 | ### 事件更新器 73 | 通过线程管理,服务器事件更新采用独立模式来更新服务器事件,采用队列模式来使得事件串行执行。 74 | 75 | 作者:好昵称不随便起 twjitm qq:1089718215 76 | 77 | 博客地址https://blog.csdn.net/baidu_23086307 78 | 79 | 个人网站地址;https://twjitm.com 80 | 81 | -------------------------------------------------------------------------------- /logs/gameExecutorEvent.log.2018-07-20: -------------------------------------------------------------------------------- 1 | 12:06:43 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@25aca718[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 2 | 12:09:01 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@4463d9d3[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 3 | -------------------------------------------------------------------------------- /logs/gameExecutorEvent.log.2018-07-21: -------------------------------------------------------------------------------- 1 | 17:28:51 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@522b2631[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 2 | 17:30:35 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@2924f1d8[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 3 | 17:31:34 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@cdb2d95[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 4 | 17:32:46 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@22a6e998[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 5 | -------------------------------------------------------------------------------- /logs/gameExecutorEvent.log.2018-07-23: -------------------------------------------------------------------------------- 1 | 17:12:08 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@69eb86b4[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 2 | 17:12:24 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@30b131b2[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 3 | 17:12:34 - #AsyncEventService disptach event id:1 4 | 17:19:28 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@cdb2d95[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 5 | 17:51:25 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@7c8326a4[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 6 | 17:51:36 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@59dc36d4[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 7 | 18:01:14 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@6ad11a56[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 8 | 18:01:42 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@65b97f47[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 9 | 19:14:53 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@1ee29c84[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 10 | 19:15:18 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@476fe690[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 11 | -------------------------------------------------------------------------------- /logs/gameExecutorEvent.log.2018-08-15: -------------------------------------------------------------------------------- 1 | 17:40:55 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@6ad11a56[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 2 | 17:42:55 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@fac80[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 3 | 17:44:25 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@65b97f47[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 4 | 18:24:45 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@6981f8f3[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 5 | -------------------------------------------------------------------------------- /logs/gameExecutorEvent.log.2018-08-16: -------------------------------------------------------------------------------- 1 | 17:11:23 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@522b2631[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 2 | 17:11:47 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@fac80[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 3 | 17:13:58 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@522b2631[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 4 | 17:14:12 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@476fe690[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 5 | 17:23:56 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@6ad11a56[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 6 | 17:24:12 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@65b97f47[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 7 | 17:35:56 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@7e74a380[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 8 | -------------------------------------------------------------------------------- /logs/gameExecutorEvent.log.2018-08-17: -------------------------------------------------------------------------------- 1 | 09:34:44 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@522b2631[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 2 | 09:35:37 - AsyncEventService processor executorService started [com.snowcattle.game.thread.executor.OrderedQueuePoolExecutor@9596ce8[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] with 60 threads ] 3 | -------------------------------------------------------------------------------- /logs/server_status: -------------------------------------------------------------------------------- 1 | 2 2018-08-20 16:19 -------------------------------------------------------------------------------- /proto/protoc-3.2.10-win32.改成zip就行: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twjitm/twjitm-core/85f60459c36028b48f1c3b47ee09d67c2befffb1/proto/protoc-3.2.10-win32.改成zip就行 -------------------------------------------------------------------------------- /src/main/assembly/assembly.xml: -------------------------------------------------------------------------------- 1 | 2 | release 3 | 4 | zip 5 | 6 | 7 | 8 | lib 9 | true 10 | false 11 | 12 | 13 | 14 | 15 | 16 | ${project.basedir}/src/main/assembly 17 | / 18 | 0755 19 | true 20 | 0755 21 | 25 | 26 | 27 | ${project.basedir}/src/main/resources 28 | 0755 29 | /config 30 | 0660 31 | 32 | 33 | ${project.basedir}/lib 34 | /lib 35 | 0755 36 | 37 | 38 | . 39 | /logs 40 | 0755 41 | 42 | */** 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /src/main/java/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: dom4j-1.6.1.jar httpcore-4.4.4.jar log4j-api-2.8.2.jar net 3 | ty-all-4.1.15.Final.jar commons-logging-1.2.jar commons-io-2.4.jar sp 4 | ring-web-4.3.9.RELEASE.jar spring-beans-4.3.9.RELEASE.jar jackson-cor 5 | e-2.8.5.jar commons-fileupload-1.3.1.jar fastjson-1.2.31.jar commons- 6 | codec-1.9.jar spring-context-4.3.9.RELEASE.jar httpclient-4.5.2.jar s 7 | pring-tx-4.3.9.RELEASE.jar protobuf-java-3.2.0.jar jackson-databind-2 8 | .8.5.jar jline-0.9.94.jar log4j-1.2.16.jar slf4j-api-1.6.1.jar slf4j- 9 | log4j12-1.6.1.jar jackson-annotations-2.8.5.jar log4j-core-2.8.2.jar 10 | spring-expression-4.3.9.RELEASE.jar spring-core-4.3.9.RELEASE.jar jav 11 | ax.servlet-api-3.1.0.jar spring-webmvc-4.3.9.RELEASE.jar log4j-web-2. 12 | 8.2.jar spring-test-4.3.9.RELEASE.jar netty-3.10.5.Final.jar zookeepe 13 | r-3.4.9.jar xml-apis-1.0.b2.jar spring-aop-4.3.9.RELEASE.jar spring-j 14 | dbc-4.3.9.RELEASE.jar javax.mail-api-1.5.5.jar 15 | Main-Class: com.twjitm.core.bootstrap.StartService 16 | 17 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/bootstrap/AbstractNettyGameBootstrapService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.bootstrap; 2 | 3 | import java.net.InetSocketAddress; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-08-16 13:50] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | * 10 | */ 11 | public abstract class AbstractNettyGameBootstrapService implements INettyBootstrapService { 12 | protected int serverPort; 13 | protected InetSocketAddress serverAddress; 14 | 15 | public AbstractNettyGameBootstrapService(int serverPort, InetSocketAddress serverAddress) { 16 | this.serverPort = serverPort; 17 | this.serverAddress = serverAddress; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/bootstrap/INettyBootstrapService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.bootstrap; 2 | 3 | /** 4 | * Created by twjitm on 2018/4/17. 5 | * Netty服务启动接口 6 | * 在服务器加载和启动的时候,调用startServer()方法的具体实现类,既可以启动服。 7 | * 在服务器启动过程中,我们首先需要加载服务器启动所需要的资源和配置文件{@link com.twjitm.core.spring.SpringServiceManager} 8 | * 利用spring来管理本地bean对象,通过单列模式的方式加载bean,提高系统资源利用率。 9 | * 在加载服务器的时候,需要将服务器的信息提交给zookeeper服务器{@link com.twjitm.core.common.zookeeper.NettyZookeeperRpcServiceRegistryService} 10 | * 同时也为获取其他服务器信息做加载{@link com.twjitm.core.common.zookeeper.NettyZookeeperRpcServiceDiscoveryService} 11 | * 12 | */ 13 | public interface INettyBootstrapService { 14 | public void startServer() throws Throwable; 15 | void stopServer()throws Throwable; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/bootstrap/http/NettyGameBootstrapHttpService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.bootstrap.http; 2 | 3 | import io.netty.channel.ChannelInitializer; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-07-27 11:30] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public class NettyGameBootstrapHttpService extends AbstractNettyGameBootstrapHttpService { 11 | 12 | 13 | public NettyGameBootstrapHttpService(int serverPort, String serverIp, String bossThreadName, String workThreadName, ChannelInitializer channelInitializer, String serverName) { 14 | super(serverPort, serverIp, bossThreadName, workThreadName, channelInitializer, serverName); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/bootstrap/info.java: -------------------------------------------------------------------------------- 1 | /**本类主要是网络服务启动类, 2 | * 主要用来监控服务器的启动,关闭,注销等操作 3 | * 一般用于打包后,设置启动类Bootstrap的main类启动类。 4 | * 5 | * 6 | * | NettyGameBootstrapTcpService 7 | * Bootstrap--------->| NettyGameBootstrapHttpService 8 | * | NettyGameBootstrapUdpService 9 | * 10 | * 11 | * 12 | * **/ -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/bootstrap/rpc/NettyGameBootstrapRpcService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.bootstrap.rpc; 2 | 3 | import com.twjitm.core.bootstrap.tcp.AbstractNettyGameBootstrapTcpService; 4 | import io.netty.channel.ChannelInitializer; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * User: 文江 Date: 2018/8/19 Time: 10:03 9 | * https://blog.csdn.net/baidu_23086307 10 | */ 11 | public class NettyGameBootstrapRpcService extends AbstractNettyGameBootstrapTcpService { 12 | 13 | public NettyGameBootstrapRpcService(int serverPort, String serverIp, String bossTreadName, String workerTreadName, ChannelInitializer channelInitializer,String serverName) { 14 | super(serverPort, serverIp, bossTreadName, workerTreadName, channelInitializer,serverName); 15 | } 16 | 17 | @Override 18 | public void startServer() { 19 | super.startServer(); 20 | 21 | } 22 | 23 | @Override 24 | public void stopServer() throws Throwable { 25 | super.stopServer(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/bootstrap/tcp/NettyGameBootstrapTcpService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.bootstrap.tcp; 2 | 3 | import io.netty.channel.ChannelInitializer; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-08-16 14:10] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public class NettyGameBootstrapTcpService extends AbstractNettyGameBootstrapTcpService { 11 | 12 | public NettyGameBootstrapTcpService(int serverPort, String serverIp, String bossTreadName, String workerTreadName, ChannelInitializer channelInitializer,String serverName) { 13 | super(serverPort, serverIp, bossTreadName, workerTreadName, channelInitializer,serverName); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/bootstrap/udp/NettyGameBootstrapUdpService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.bootstrap.udp; 2 | 3 | import io.netty.channel.ChannelInitializer; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-08-16 14:41] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public class NettyGameBootstrapUdpService extends AbstractNettyGameBootstrapUdpService { 11 | public NettyGameBootstrapUdpService(int serverPort, String serverIp, String threadName, ChannelInitializer channelInitializer,String serverName) { 12 | super(serverPort, serverIp, threadName, channelInitializer,serverName); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/annotation/MessageCommandAnnotation.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.annotation; 2 | 3 | import com.twjitm.core.common.enums.MessageComm; 4 | 5 | import java.lang.annotation.Documented; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | 9 | /** 10 | * 消息分离注解 11 | */ 12 | @Retention(RetentionPolicy.RUNTIME) 13 | @Documented 14 | public @interface MessageCommandAnnotation { 15 | MessageComm messageCmd(); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/annotation/NettyRpcServiceAnnotation.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.annotation; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | /** 11 | * Created by IntelliJ IDEA. 12 | * User: 文江 Date: 2018/8/19 Time: 13:19 13 | * https://blog.csdn.net/baidu_23086307 14 | * rpc service annotation 15 | */ 16 | @Target({ElementType.TYPE}) 17 | @Retention(RetentionPolicy.RUNTIME) 18 | @Component 19 | public @interface NettyRpcServiceAnnotation { 20 | Class> value(); 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/check/NettyLifeCycleCheckService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.check; import com.twjitm.core.common.config.global.GlobalConstants; import com.twjitm.core.common.config.global.NettyGameServiceConfigService; import com.twjitm.core.common.service.IService; import com.twjitm.core.spring.SpringServiceManager; import com.twjitm.core.utils.time.timer.PollTimer; import org.springframework.stereotype.Service; /** * 生命周期检测 * * @author twjitm - [Created on 2018-08-31 10:21] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ @Service public class NettyLifeCycleCheckService implements IService { /** * 周期时间轮询器 */ private PollTimer pollTimer; /** * 是否开放 */ private boolean open; @Override public String getId() { return NettyLifeCycleCheckService.class.getSimpleName(); } @Override public void startup() throws Exception { NettyGameServiceConfigService config = SpringServiceManager.getSpringLoadService() .getNettyGameServiceConfigService(); open = config.getNettyGameServiceConfig().isLifeCycleOpen(); if (open) { pollTimer = new PollTimer<>( GlobalConstants.PollTimer.tickDuration, GlobalConstants.PollTimer.timeUnit, GlobalConstants.PollTimer.ticksPerPoll); pollTimer.start(); } } @Override public void shutdown() throws Exception { if (open) { pollTimer.stop(); } } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/config/global/GameWebSocketConfig.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.config.global; /** * @author twjitm - [Created on 2018-08-22 17:43] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class GameWebSocketConfig { } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/config/global/KafkaConfig.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.config.global; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.Properties; /** * kafka 配置 * * @author twjitm - [Created on 2018-09-04 14:17] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ @Service public class KafkaConfig { private int taskThreadSize; private int corePoolSize; private int maximumPoolSize; private int keepAliveTime; public void init() { Properties properties = new Properties(); try { properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(GlobalConstants.ConfigFile.KAFKA_PROPERTIES_FILE_PATH)); taskThreadSize = Integer.parseInt(properties.getProperty("kafka.taskThreadSize")); corePoolSize = Integer.parseInt(properties.getProperty("kafka.corePoolSize")); maximumPoolSize = Integer.parseInt(properties.getProperty("kafka.maximumPoolSize")); keepAliveTime = Integer.parseInt(properties.getProperty("kafka.keepAliveTime")); } catch (IOException e) { e.printStackTrace(); } } public int getTaskThreadSize() { return taskThreadSize; } public int getCorePoolSize() { return corePoolSize; } public int getMaximumPoolSize() { return maximumPoolSize; } public int getKeepAliveTime() { return keepAliveTime; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/config/global/NettyGameConfig.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.config.global; import org.jdom2.Element; /** * @author twjitm - [Created on 2018-08-22 18:27] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class NettyGameConfig { private String serverName; private String serverId; private String serverHost; private int serverPort; public void init(Element element){ serverName = element.getChildTextTrim("name"); serverId = element.getChildTextTrim("serverId"); serverHost = element.getChildTextTrim("ip"); serverPort = Integer.parseInt(element.getChildTextTrim("port")); } public String getServerName() { return serverName; } public String getServerId() { return serverId; } public String getServerHost() { return serverHost; } public int getServerPort() { return serverPort; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/config/global/NettyGameHttpConfig.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.config.global; import com.twjitm.core.utils.xml.JdomUtils; import org.jdom2.Element; import org.springframework.stereotype.Service; /** * @author twjitm - [Created on 2018-08-22 17:43] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ @Service public class NettyGameHttpConfig extends NettyGameConfig { private boolean openSSL; private int handleThreadSize; public void init() { String file = GlobalConstants.ConfigFile.HTTP_SERVER_CONFIG; Element rootElement = JdomUtils.getRootElementByStream(file); Element element = rootElement.getChild("server"); super.init(element); openSSL = Boolean.parseBoolean(element.getChildTextTrim("openSSL")); handleThreadSize = Integer.parseInt(element.getChildTextTrim("handleThreadSize")); } public boolean isOpenSSL() { return openSSL; } public int getHandleThreadSize() { return handleThreadSize; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/config/global/NettyGameRpcConfig.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.config.global; import com.twjitm.core.utils.xml.JdomUtils; import org.jdom2.Element; import org.springframework.stereotype.Service; /** * @author twjitm - [Created on 2018-08-22 19:14] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" * rpc 网络配置 */ @Service public class NettyGameRpcConfig extends NettyGameConfig { public void init() { String file = GlobalConstants.ConfigFile.RPC_SERVER_CONFIG_FILE_PATH; Element rootElement = JdomUtils.getRootElementByStream(file); super.init(rootElement); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/config/global/NettyGameUdpConfig.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.config.global; import com.twjitm.core.utils.xml.JdomUtils; import org.jdom2.Element; import org.springframework.stereotype.Service; /** * @author twjitm - [Created on 2018-08-22 17:42] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ @Service public class NettyGameUdpConfig extends NettyGameConfig { /** * udp消息处理器工作线程大小 */ private int updQueueMessageProcessWorkerSize; /** * udp消息出路方式:true:有序队列。false:线程池生产者消费者阻塞队列 */ private boolean messageInOrderQueue; public void init() { Element rootElement = JdomUtils.getRootElementByStream(GlobalConstants.ConfigFile.UDP_SERVER_CONFIG_FILE_PATH); Element element = rootElement.getChild("server"); super.init(element); updQueueMessageProcessWorkerSize = Integer.parseInt(element.getChildTextTrim("queueWorkSize")); messageInOrderQueue = Boolean.parseBoolean(element.getChildTextTrim("orderFlag")); } public int getUpdQueueMessageProcessWorkerSize() { return updQueueMessageProcessWorkerSize; } public boolean isMessageInOrderQueue() { return messageInOrderQueue; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/config/rpc/RpcSystemConfig.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.config.rpc; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: 文江 Date: 2018/8/19 Time: 10:43 6 | * https://blog.csdn.net/baidu_23086307 7 | */ 8 | public class RpcSystemConfig { 9 | 10 | public static final String SystemPropertyThreadPoolRejectedPolicyAttr = "com.twjitm.core.rpc.parallel.rejected.policy"; 11 | public static final String SystemPropertyThreadPoolQueueNameAttr = "com.twjitm.core.rpc.parallel.queue"; 12 | public static final int PARALLEL = Math.max(2, Runtime.getRuntime().availableProcessors()); 13 | 14 | private static boolean monitorServerSupport = false; 15 | 16 | public static boolean isMonitorServerSupport() { 17 | return monitorServerSupport; 18 | } 19 | 20 | public static void setMonitorServerSupport(boolean jmxSupport) { 21 | monitorServerSupport = jmxSupport; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/entity/IMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.entity; 2 | 3 | public interface IMessage { 4 | /** 5 | * SESSION_ID 6 | * @return 7 | */ 8 | public long getSessionId(); 9 | /** 10 | * 命令号 11 | * @return 12 | */ 13 | public int getCommandId(); 14 | 15 | /** 16 | * 序列号 17 | * @return 18 | */ 19 | public int getSerial(); 20 | 21 | /** 22 | * 玩家id 23 | */ 24 | public long getUserId(); 25 | 26 | /** 27 | * 释放 28 | */ 29 | public void release(); 30 | 31 | /** 32 | * 信息 33 | */ 34 | public String toAllInfoString(); 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/entity/chat/BoradCastAllChatMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.entity.chat; 2 | 3 | 4 | import com.twjitm.core.common.annotation.MessageCommandAnnotation; 5 | import com.twjitm.core.common.enums.MessageComm; 6 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 7 | import io.netty.handler.codec.CodecException; 8 | 9 | import java.util.List; 10 | 11 | @MessageCommandAnnotation(messageCmd = MessageComm.PUBLIC_CHART_MESSAGE) 12 | public class BoradCastAllChatMessage extends AbstractNettyNetProtoBufMessage { 13 | private List messages; 14 | 15 | 16 | 17 | public List getMessages() { 18 | return messages; 19 | } 20 | 21 | public void setMessages(List messages) { 22 | this.messages = messages; 23 | } 24 | 25 | 26 | 27 | public void release() throws CodecException { 28 | 29 | } 30 | 31 | public void encodeNetProtoBufMessageBody() throws CodecException, Exception { 32 | 33 | } 34 | 35 | public void decoderNetProtoBufMessageBody() throws CodecException, Exception { 36 | 37 | } 38 | 39 | public void decoderNetJsonMessageBody(String json) { 40 | 41 | } 42 | 43 | public void encodeNetJsonMessageBody(String json) { 44 | 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/entity/chat/DeleteChatMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.entity.chat; 2 | 3 | import com.twjitm.core.common.annotation.MessageCommandAnnotation; 4 | import com.twjitm.core.common.enums.MessageComm; 5 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 6 | import io.netty.handler.codec.CodecException; 7 | 8 | /** 9 | * 删除聊天消息 10 | */ 11 | @MessageCommandAnnotation(messageCmd = MessageComm.DELETE_CHAT_MESSAGE) 12 | public class DeleteChatMessage extends AbstractNettyNetProtoBufMessage { 13 | 14 | 15 | 16 | 17 | public void decoderNetJsonMessageBody(String json) { 18 | 19 | } 20 | 21 | public void encodeNetJsonMessageBody(String json) { 22 | 23 | } 24 | 25 | public void release() throws CodecException { 26 | 27 | } 28 | 29 | public void encodeNetProtoBufMessageBody() throws CodecException, Exception { 30 | 31 | } 32 | 33 | public void decoderNetProtoBufMessageBody() throws CodecException, Exception { 34 | 35 | } 36 | 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/entity/chat/GroupChatMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.entity.chat; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | 5 | /** 6 | * Created by 文江 on 2017/11/5. 7 | */ 8 | public class GroupChatMessage extends ChatMessage { 9 | private long groupId; 10 | 11 | 12 | 13 | public GroupChatMessage(String json) { 14 | 15 | GroupChatMessage chatMessage = (GroupChatMessage) JSON.parse(json); 16 | this.groupId = chatMessage.getGroupId(); 17 | 18 | } 19 | 20 | public long getGroupId() { 21 | return groupId; 22 | } 23 | 24 | public void setGroupId(long groupId) { 25 | this.groupId = groupId; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/entity/chat/ResponseErrorMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.entity.chat; 2 | 3 | import com.twjitm.core.common.annotation.MessageCommandAnnotation; 4 | import com.twjitm.core.common.enums.MessageComm; 5 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 6 | import io.netty.handler.codec.CodecException; 7 | 8 | /** 9 | * Created by 文江 on 2017/11/8. 10 | */ 11 | 12 | /** 13 | * 异常返回消息统一对象 14 | */ 15 | @MessageCommandAnnotation(messageCmd = MessageComm.MESSAGE_TRUE_RETURN) 16 | public class ResponseErrorMessage extends AbstractNettyNetProtoBufMessage { 17 | 18 | private short errorCode; 19 | private byte errType; 20 | private String message; 21 | 22 | public ResponseErrorMessage() { 23 | super(); 24 | } 25 | 26 | @Override 27 | public void release() throws CodecException { 28 | 29 | } 30 | 31 | @Override 32 | public void encodeNetProtoBufMessageBody() throws CodecException, Exception { 33 | } 34 | 35 | @Override 36 | public void decoderNetProtoBufMessageBody() throws CodecException, Exception { 37 | 38 | } 39 | 40 | public short getErrorCode() { 41 | return errorCode; 42 | } 43 | 44 | public void setErrorCode(short errorCode) { 45 | this.errorCode = errorCode; 46 | } 47 | 48 | public byte getErrType() { 49 | return errType; 50 | } 51 | 52 | public void setErrType(byte errType) { 53 | this.errType = errType; 54 | } 55 | 56 | public String getMessage() { 57 | return message; 58 | } 59 | 60 | public void setMessage(String message) { 61 | this.message = message; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/entity/chat/ResponseMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.entity.chat; 2 | 3 | import com.twjitm.core.common.annotation.MessageCommandAnnotation; 4 | import com.twjitm.core.common.enums.MessageComm; 5 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 6 | import io.netty.handler.codec.CodecException; 7 | 8 | /** 9 | * Created by 文江 on 2017/11/8. 10 | */ 11 | 12 | /** 13 | * 正常返回消息对象 14 | */ 15 | @MessageCommandAnnotation(messageCmd = MessageComm.MESSAGE_TRUE_RETURN) 16 | public class ResponseMessage extends AbstractNettyNetProtoBufMessage { 17 | 18 | 19 | 20 | @Override 21 | public void release() throws CodecException { 22 | 23 | } 24 | 25 | @Override 26 | public void encodeNetProtoBufMessageBody() throws CodecException, Exception { 27 | } 28 | 29 | @Override 30 | public void decoderNetProtoBufMessageBody() throws CodecException, Exception { 31 | 32 | } 33 | 34 | public void decoderNetJsonMessageBody(String json) { 35 | 36 | } 37 | 38 | public void encodeNetJsonMessageBody(String json) { 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/entity/online/LoginOnlineClientTcpMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.entity.online; 2 | 3 | import com.twjitm.core.common.annotation.MessageCommandAnnotation; 4 | import com.twjitm.core.common.enums.MessageComm; 5 | import com.twjitm.core.common.netstack.entity.tcp.AbstractNettyNetProtoBufTcpMessage; 6 | import com.twjitm.core.common.proto.LoginOnlineClientTcpMessagebuf; 7 | import io.netty.handler.codec.CodecException; 8 | 9 | /** 10 | * @author twjitm - [Created on 2018-08-08 17:41] 11 | * @company https://github.com/twjitm/ 12 | * @jdk java version "1.8.0_77" 13 | */ 14 | @MessageCommandAnnotation(messageCmd = MessageComm.PLAYER_LOGIN_MESSAGE) 15 | public class LoginOnlineClientTcpMessage extends AbstractNettyNetProtoBufTcpMessage { 16 | private long playerId; 17 | 18 | 19 | @Override 20 | public void release() throws CodecException { 21 | 22 | } 23 | 24 | @Override 25 | public void encodeNetProtoBufMessageBody() throws CodecException, Exception { 26 | LoginOnlineClientTcpMessagebuf.LoginOnlineClientTcpMessage.Builder builder = LoginOnlineClientTcpMessagebuf.LoginOnlineClientTcpMessage.newBuilder(); 27 | builder.setPlayerId(playerId); 28 | byte[] bytes=builder.build().toByteArray(); 29 | this.getNetMessageBody().setBytes(bytes); 30 | } 31 | 32 | @Override 33 | public void decoderNetProtoBufMessageBody() throws CodecException, Exception { 34 | byte[] bytes = getNetMessageBody().getBytes(); 35 | LoginOnlineClientTcpMessagebuf.LoginOnlineClientTcpMessage req = LoginOnlineClientTcpMessagebuf.LoginOnlineClientTcpMessage.parseFrom(bytes); 36 | playerId = req.getPlayerId(); 37 | } 38 | 39 | public long getPlayerId() { 40 | return playerId; 41 | } 42 | 43 | public void setPlayerId(long playerId) { 44 | this.playerId = playerId; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/entity/online/OnlineHeartClientHttpMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.entity.online; 2 | 3 | import com.twjitm.core.common.annotation.MessageCommandAnnotation; 4 | import com.twjitm.core.common.enums.MessageComm; 5 | import com.twjitm.core.common.netstack.entity.http.AbstractNettyNetProtoBufHttpMessage; 6 | import com.twjitm.core.common.proto.OnlineHeratClientHttpMessageBuf; 7 | import io.netty.handler.codec.CodecException; 8 | 9 | /** 10 | * @author twjitm - [Created on 2018-08-16 16:00] 11 | * @company https://github.com/twjitm/ 12 | * @jdk java version "1.8.0_77" 13 | */ 14 | @MessageCommandAnnotation(messageCmd = MessageComm.HTTP_ONLINE_HEART_MESSAGE) 15 | public class OnlineHeartClientHttpMessage extends AbstractNettyNetProtoBufHttpMessage { 16 | private long playerId; 17 | private String playerName; 18 | 19 | @Override 20 | public void release() throws CodecException { 21 | 22 | } 23 | 24 | @Override 25 | public void encodeNetProtoBufMessageBody() throws CodecException, Exception { 26 | OnlineHeratClientHttpMessageBuf.OnlineClientHttpMessage.Builder builder = OnlineHeratClientHttpMessageBuf.OnlineClientHttpMessage.newBuilder(); 27 | builder.setPlayerId(this.getPlayerId()); 28 | builder.setPlayerName(this.getPlayerName()); 29 | byte[] bytes = builder.build().toByteArray(); 30 | getNetMessageBody().setBytes(bytes); 31 | } 32 | 33 | @Override 34 | public void decoderNetProtoBufMessageBody() throws CodecException, Exception { 35 | byte[] bytes = getNetMessageBody().getBytes(); 36 | OnlineHeratClientHttpMessageBuf.OnlineClientHttpMessage message = OnlineHeratClientHttpMessageBuf.OnlineClientHttpMessage.parseFrom(bytes); 37 | this.playerId = message.getPlayerId(); 38 | this.playerName = message.getPlayerName(); 39 | } 40 | 41 | public void setPlayerId(long playerId) { 42 | this.playerId = playerId; 43 | } 44 | 45 | public void setPlayerName(String playerName) { 46 | this.playerName = playerName; 47 | } 48 | 49 | public long getPlayerId() { 50 | return playerId; 51 | } 52 | 53 | public String getPlayerName() { 54 | return playerName; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/entity/online/OnlineMessageUdpMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.entity.online; 2 | 3 | import com.twjitm.core.common.annotation.MessageCommandAnnotation; 4 | import com.twjitm.core.common.enums.MessageComm; 5 | import com.twjitm.core.common.netstack.entity.udp.AbstractNettyNetProtoBufUdpMessage; 6 | import com.twjitm.core.common.proto.OnlineClientUdpMessageBuf; 7 | import io.netty.handler.codec.CodecException; 8 | 9 | /** 10 | * @author twjitm - [Created on 2018-08-14 14:31] 11 | * @company https://github.com/twjitm/ 12 | * @jdk java version "1.8.0_77" 13 | */ 14 | @MessageCommandAnnotation(messageCmd = MessageComm.UDP_ONLINE_HEART_MESSAGE) 15 | public class OnlineMessageUdpMessage extends AbstractNettyNetProtoBufUdpMessage { 16 | private long id; 17 | 18 | @Override 19 | public void release() throws CodecException { 20 | 21 | } 22 | 23 | @Override 24 | public void encodeNetProtoBufMessageBody() throws CodecException, Exception { 25 | OnlineClientUdpMessageBuf.OnlineClientUdpMessage.Builder builder = OnlineClientUdpMessageBuf.OnlineClientUdpMessage.newBuilder(); 26 | this.id = builder.getId(); 27 | builder.setId(this.getId()); 28 | byte[] bytes = builder.build().toByteArray(); 29 | getNetMessageBody().setBytes(bytes); 30 | 31 | } 32 | 33 | @Override 34 | public void decoderNetProtoBufMessageBody() throws CodecException, Exception { 35 | byte[] bytes = getNetMessageBody().getBytes(); 36 | OnlineClientUdpMessageBuf.OnlineClientUdpMessage message = OnlineClientUdpMessageBuf.OnlineClientUdpMessage.parseFrom(bytes); 37 | setId(message.getId()); 38 | 39 | } 40 | 41 | public long getId() { 42 | return id; 43 | } 44 | 45 | public void setId(long id) { 46 | this.id = id; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/entity/online/OnlineUserBroadCastMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.entity.online; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 5 | import io.netty.handler.codec.CodecException; 6 | 7 | /** 8 | * 玩家广播上线/下现消息 9 | */ 10 | public class OnlineUserBroadCastMessage extends AbstractNettyNetProtoBufMessage { 11 | 12 | private int outOrInType;//类型 13 | private long messageTime;//时间 14 | 15 | public OnlineUserBroadCastMessage() { 16 | } 17 | 18 | public void release() throws CodecException { 19 | 20 | } 21 | 22 | public void encodeNetProtoBufMessageBody() throws CodecException, Exception { 23 | 24 | } 25 | 26 | public void decoderNetProtoBufMessageBody() throws CodecException, Exception { 27 | 28 | } 29 | 30 | 31 | 32 | 33 | 34 | public void decodeBody(Object in) { 35 | 36 | } 37 | 38 | public void encodeBody(Object out) { 39 | 40 | } 41 | 42 | /*public User getUser() { 43 | return user; 44 | } 45 | 46 | public void setUser(User user) { 47 | this.user = user; 48 | }*/ 49 | 50 | public int getOutOrInType() { 51 | return outOrInType; 52 | } 53 | 54 | public void setOutOrInType(int outOrInType) { 55 | this.outOrInType = outOrInType; 56 | } 57 | 58 | public long getMessageTime() { 59 | return messageTime; 60 | } 61 | 62 | public void setMessageTime(long messageTime) { 63 | this.messageTime = messageTime; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/entity/online/OnlineUserPo.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.entity.online; 2 | 3 | import io.netty.channel.Channel; 4 | 5 | /** 6 | * Created by 文江 on 2017/10/28. 7 | */ 8 | public class OnlineUserPo { 9 | private Channel channel; 10 | private String sessionId; 11 | private long uId; 12 | 13 | public Channel getChannel() { 14 | return channel; 15 | } 16 | 17 | public void setChannel(Channel channel) { 18 | this.channel = channel; 19 | } 20 | 21 | public String getSessionId() { 22 | return sessionId; 23 | } 24 | 25 | public void setSessionId(String sessionId) { 26 | this.sessionId = sessionId; 27 | } 28 | 29 | public long getuId() { 30 | return uId; 31 | } 32 | 33 | public void setuId(long uId) { 34 | this.uId = uId; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/enums/MessageAttributeEnum.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.enums; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-08-06 21:20] 5 | * @company https://github.com/twjitm/ 6 | * @jdk java version "1.8.0_77" 7 | */ 8 | public enum MessageAttributeEnum { 9 | /** 10 | * tcp跟udp使用 11 | */ 12 | DISPATCH_SESSION, 13 | 14 | /** 15 | * http使用 16 | */ 17 | DISPATCH_HTTP_REQUEST, 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/enums/MessageComm.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.enums; 2 | 3 | /** 4 | * Created by 文江 on 2017/11/5. 5 | */ 6 | public enum MessageComm { 7 | //tcp协议0-3000 8 | MESSAGE_TRUE_RETURN(0), 9 | PUBLIC_CHART_MESSAGE(1), 10 | PRIVATE_CHAT_MESSAGE(2), 11 | PLAYER_LOGIN_MESSAGE(3), 12 | PLAYER_LOGOUT_MESSAGE(4), 13 | DELETE_CHAT_MESSAGE(5), 14 | HEART_MESSAGE(6), 15 | 16 | 17 | 18 | //udp协议 19 | UDP_TEST_COMM(2001), 20 | UDP_ONLINE_HEART_MESSAGE(2002) 21 | 22 | , 23 | 24 | //http协议3001-4001 max;32767 25 | HTTP_ONLINE_HEART_MESSAGE(3001) 26 | ,; 27 | 28 | 29 | 30 | public int commId; 31 | 32 | MessageComm(int commId) { 33 | this.commId = commId; 34 | } 35 | 36 | public static int getVaule(MessageComm messageComm) { 37 | return messageComm.commId; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/enums/MessageType.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.enums; 2 | 3 | /** 4 | * 消息类型处理 5 | */ 6 | public interface MessageType { 7 | /** 8 | * 聊天消息类型 9 | */ 10 | public int CHAT_MESSAGE = 0; 11 | /** 12 | * 群聊 13 | */ 14 | public int PUBLIC_CHART_MESSAGE = 1; 15 | /** 16 | * 单聊 17 | */ 18 | public int PRIVATE_CHAT_MESSAGE = 2; 19 | /** 20 | * 玩家登录 21 | */ 22 | public int PLAYER_LOGIN_MESSAGE = 3; 23 | /** 24 | * 玩家退出登录 25 | */ 26 | public int PLAYER_LOGOUT_MESSAGE = 4; 27 | /** 28 | * 心跳协议 29 | */ 30 | public int HEART_MESSAGE = 5; 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/enums/NettyGameTypeEnum.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.enums; /** * @author twjitm - [Created on 2018-08-20 12:29] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public enum NettyGameTypeEnum { //网关 PROXY(1), //世界 WORLD(2), //游戏 GAME(3), //db DB(4), ; private int boId; NettyGameTypeEnum(int boId) { this.boId = boId; } public int getBoId() { return boId; } public void setBoId(int boId) { this.boId = boId; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/factory/INettyTcpMessageFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.factory; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-07-26 21:03] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public interface INettyTcpMessageFactory { 11 | /** 12 | * 创建一个错误消息 13 | * 14 | * @param serial 15 | * @param state 16 | * @param tip 17 | * @return 18 | */ 19 | public AbstractNettyNetMessage createCommonErrorResponseMessage(int serial, int state, String tip); 20 | 21 | public AbstractNettyNetMessage createCommonErrorResponseMessage(int serial, int state); 22 | 23 | /** 24 | * 创建一个正常返回消息 25 | * 26 | * @param serial 27 | * @return 28 | */ 29 | public AbstractNettyNetMessage createCommonResponseMessage(int serial); 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/factory/NettyTcpMessageFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.factory; 2 | 3 | import com.twjitm.core.common.entity.chat.ResponseErrorMessage; 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 5 | import org.springframework.stereotype.Service; 6 | 7 | /** 8 | * @author twjitm - [Created on 2018-07-26 21:04] 9 | * @company https://github.com/twjitm/ 10 | * @jdk java version "1.8.0_77" 11 | */ 12 | @Service 13 | public class NettyTcpMessageFactory implements INettyTcpMessageFactory { 14 | @Override 15 | public AbstractNettyNetMessage createCommonErrorResponseMessage(int serial, int state, String tip) { 16 | ResponseErrorMessage message = new ResponseErrorMessage(); 17 | message.setSerial(serial); 18 | message.setErrorCode((short) 500); 19 | message.setMessage(tip); 20 | return message; 21 | } 22 | 23 | @Override 24 | public AbstractNettyNetMessage createCommonErrorResponseMessage(int serial, int state) { 25 | ResponseErrorMessage message = new ResponseErrorMessage(); 26 | message.setSerial(serial); 27 | message.setErrorCode((short) 500); 28 | message.setMessage("default"); 29 | return message; 30 | } 31 | 32 | @Override 33 | public AbstractNettyNetMessage createCommonResponseMessage(int serial) { 34 | ResponseErrorMessage message = new ResponseErrorMessage(); 35 | message.setSerial(serial); 36 | message.setErrorCode((short) 200); 37 | message.setMessage("successful"); 38 | return message; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/factory/classload/DynamicGameClassLoader.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.factory.classload; 2 | 3 | import org.slf4j.Logger; 4 | 5 | import java.util.Hashtable; 6 | 7 | /** 8 | * 动态游戏工厂 9 | */ 10 | public class DynamicGameClassLoader extends ClassLoader { 11 | 12 | //public static final Logger logger = Loggers.serverLogger; 13 | 14 | private Hashtable loadedClasses = new Hashtable(); 15 | 16 | public Class> findClass(String className, byte[] b) throws ClassNotFoundException { 17 | //logger.info("class loader find:" + className); 18 | Class> classes = defineClass(null, b, 0, b.length); 19 | loadedClasses.put(className, classes); 20 | return classes; 21 | } 22 | 23 | @Override 24 | public synchronized Class loadClass(String className, boolean resolve) throws ClassNotFoundException { 25 | //logger.info("class loader init:" + className); 26 | return super.loadClass(className, resolve); 27 | } 28 | 29 | @Override 30 | protected Class> findClass(final String className) throws ClassNotFoundException{ 31 | if(loadedClasses.containsKey(className)){ 32 | return loadedClasses.get(className); 33 | } 34 | return super.findClass(className); 35 | } 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/factory/classload/NettyClassloader.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.factory.classload; 2 | 3 | import com.twjitm.core.common.utils.PackageScaner; 4 | 5 | /** 6 | * Created by 文江 on 2017/11/9. 7 | * 扩展类加载器,加载class文件 8 | */ 9 | public class NettyClassloader extends ClassLoader { 10 | 11 | public Class> findclss(byte[] b) { 12 | return defineClass(null, b, 0, b.length); 13 | } 14 | 15 | 16 | public String[] scannerPackage(String namespace, String ext) throws Exception 17 | { 18 | String[] files = new PackageScaner().scanNamespaceFiles(namespace, ext, false, true); 19 | return files; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/factory/thread/async/AsyncCall.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.factory.thread.async; /** * @author twjitm - [Created on 2018-08-20 10:43] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public interface AsyncCall extends Runnable { void asyncCall() throws Exception; } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/factory/thread/async/poll/AsyncThreadPool.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.factory.thread.async.poll; 2 | 3 | 4 | import com.twjitm.core.common.factory.thread.async.AsyncCall; 5 | 6 | import java.util.concurrent.Future; 7 | 8 | /** 9 | * Created by twjitm on 17/4/19. 10 | * 异步线程池 11 | */ 12 | public interface AsyncThreadPool { 13 | public Future submit(AsyncCall asyncCall); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/factory/thread/async/poll/AsyncThreadService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.factory.thread.async.poll; 2 | 3 | import com.twjitm.core.common.config.global.GlobalConstants; 4 | import com.twjitm.core.common.config.global.NettyGameServiceConfig; 5 | import com.twjitm.core.common.config.global.NettyGameServiceConfigService; 6 | import com.twjitm.core.common.factory.thread.async.AsyncCall; 7 | import com.twjitm.core.common.service.IService; 8 | import com.twjitm.core.spring.SpringServiceManager; 9 | import com.twjitm.threads.thread.NettyThreadNameFactory; 10 | import com.twjitm.threads.utils.ExecutorUtil; 11 | import org.springframework.stereotype.Service; 12 | 13 | import java.util.concurrent.*; 14 | 15 | /** 16 | * Created by twjitm on 17/4/19. 17 | * 增加异步线程池 18 | */ 19 | @Service 20 | public class AsyncThreadService implements AsyncThreadPool, IService { 21 | 22 | protected ExecutorService executorService; 23 | 24 | 25 | @Override 26 | public Future submit(AsyncCall asyncCall) { 27 | return executorService.submit(asyncCall); 28 | } 29 | 30 | @Override 31 | public String getId() { 32 | return ""; 33 | } 34 | 35 | @Override 36 | public void startup() throws Exception { 37 | NettyGameServiceConfigService gameServerConfigService = SpringServiceManager.getSpringLoadService().getNettyGameServiceConfigService(); 38 | NettyGameServiceConfig gameServerConfig = gameServerConfigService.getNettyGameServiceConfig(); 39 | NettyThreadNameFactory nettyThreadNameFactory = new NettyThreadNameFactory(GlobalConstants.Thread.GAME_ASYNC_CALL); 40 | executorService = new ThreadPoolExecutor(gameServerConfig.getAsyncThreadPoolCoreSize(), gameServerConfig.getAsyncThreadPoolMaxSize(),60L, TimeUnit.SECONDS,new LinkedBlockingQueue(), nettyThreadNameFactory); 41 | } 42 | 43 | @Override 44 | public void shutdown() throws Exception { 45 | ExecutorUtil.shutdownAndAwaitTermination(this.executorService, 60, TimeUnit.SECONDS); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/handler/http/AbstractNettyNetMessageHttpServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.handler.http; 2 | 3 | import io.netty.channel.SimpleChannelInboundHandler; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-08-14 17:09] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public abstract class AbstractNettyNetMessageHttpServerHandler extends SimpleChannelInboundHandler { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/handler/infor.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/handler/rpc/NettyRpcClientServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.handler.rpc; import com.twjitm.core.common.netstack.entity.rpc.NettyRpcResponseMessage; import com.twjitm.core.common.service.rpc.network.NettyRpcClient; import com.twjitm.core.utils.logs.LoggerUtils; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import org.apache.log4j.Logger; /** * @author twjitm - [Created on 2018-08-20 11:30] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class NettyRpcClientServerHandler extends SimpleChannelInboundHandler { private NettyRpcClient nettyRpcClient; private Logger logger=LoggerUtils.getLogger(NettyRpcClientServerHandler.class); @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { super.channelRegistered(ctx); } @Override public void channelRead0(ChannelHandlerContext ctx, NettyRpcResponseMessage response) throws Exception { nettyRpcClient.handleRpcResponse(response); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error("RPC CLIENT CAUGHT EXCEPTION", cause); nettyRpcClient.close(); } public NettyRpcClient getNettyRpcClient() { return nettyRpcClient; } public void setNettyRpcClient(NettyRpcClient nettyRpcClient) { this.nettyRpcClient = nettyRpcClient; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/handler/tcp/NettyNetLoggingHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.handler.tcp; 2 | 3 | import io.netty.channel.ChannelFuture; 4 | import io.netty.channel.ChannelFutureListener; 5 | import io.netty.channel.ChannelHandlerContext; 6 | import io.netty.channel.ChannelPromise; 7 | import io.netty.handler.logging.LogLevel; 8 | import io.netty.handler.logging.LoggingHandler; 9 | import org.apache.log4j.Logger; 10 | 11 | /** 12 | * @author twjitm - [Created on 2018-08-15 18:20] 13 | * @company https://github.com/twjitm/ 14 | * @jdk java version "1.8.0_77" 15 | */ 16 | public class NettyNetLoggingHandler extends LoggingHandler { 17 | private Logger logger=Logger.getLogger(NettyNetLoggingHandler.class); 18 | 19 | public NettyNetLoggingHandler(LogLevel level) { 20 | super(level); 21 | } 22 | private final ChannelFutureListener exceptionListener = new ChannelFutureListener() { 23 | @Override 24 | public void operationComplete(ChannelFuture future) throws Exception { 25 | if(!future.isSuccess()){ 26 | Throwable throwable = future.cause(); 27 | if(throwable != null) { 28 | logger.error(throwable.toString(), throwable); 29 | } 30 | } 31 | } 32 | }; 33 | @Override 34 | public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { 35 | if (logger.isDebugEnabled()) { 36 | logger.info(msg); 37 | } 38 | ChannelPromise unvoId = promise.unvoid(); 39 | unvoId.addListener(exceptionListener); 40 | ctx.write(msg, promise); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/handler/tcp/NettyNetMessageTcpServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.handler.tcp; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import com.twjitm.core.common.netstack.pipeline.INettyServerPipeLine; 5 | import com.twjitm.core.common.netstack.pipeline.NettyTcpServerPipeLineImpl; 6 | import com.twjitm.core.common.netstack.session.tcp.NettyTcpSession; 7 | import com.twjitm.core.service.dispatcher.IDispatcherService; 8 | import com.twjitm.core.spring.SpringServiceManager; 9 | import io.netty.channel.ChannelHandlerContext; 10 | 11 | import javax.annotation.Resource; 12 | 13 | /** 14 | * @author twjitm - [Created on 2018-07-26 21:11] 15 | * @company https://github.com/twjitm/ 16 | * @jdk java version "1.8.0_77" 17 | */ 18 | public class NettyNetMessageTcpServerHandler extends AbstractNettyNetMessageTcpServerHandler { 19 | 20 | @Override 21 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 22 | AbstractNettyNetMessage message = (AbstractNettyNetMessage) msg; 23 | INettyServerPipeLine nettyTcpServerPipeLine = SpringServiceManager.springLoadService.getNettyTcpServerPipeLine(); 24 | nettyTcpServerPipeLine.dispatch(ctx.channel(), message); 25 | } 26 | 27 | @Override 28 | public void addUpdateSession(NettyTcpSession nettyTcpSession) { 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/handler/udp/AbstractNettyNetMessageUdpServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.handler.udp; 2 | 3 | import io.netty.channel.ChannelInboundHandlerAdapter; 4 | import io.netty.channel.SimpleChannelInboundHandler; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-07-30 11:36] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | */ 11 | public abstract class AbstractNettyNetMessageUdpServerHandler extends SimpleChannelInboundHandler { 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/handler/udp/NettyNetMessageUdpServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.handler.udp; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import com.twjitm.core.common.netstack.entity.udp.AbstractNettyNetProtoBufUdpMessage; 5 | import com.twjitm.core.common.netstack.pipeline.INettyServerPipeLine; 6 | import com.twjitm.core.spring.SpringServiceManager; 7 | import io.netty.channel.ChannelHandlerContext; 8 | import org.apache.log4j.Logger; 9 | 10 | /** 11 | * @author twjitm - [Created on 2018-07-30 11:37] 12 | * @company https://github.com/twjitm/ 13 | * @jdk java version "1.8.0_77" 14 | */ 15 | 16 | public class NettyNetMessageUdpServerHandler extends AbstractNettyNetMessageUdpServerHandler { 17 | Logger logger = Logger.getLogger(NettyNetMessageUdpServerHandler.class); 18 | 19 | @Override 20 | protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { 21 | //获取处理管道 22 | INettyServerPipeLine udpServerPipeLine = SpringServiceManager.springLoadService.getNettyUdpServerPipeLine(); 23 | udpServerPipeLine.dispatch(ctx.channel(), (AbstractNettyNetMessage) msg); 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/kafka/AbstractKafkaPushTask.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.kafka; /** * @author twjitm - [Created on 2018-09-04 21:31] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public abstract class AbstractKafkaPushTask { private KafkaTaskType taskType; public Object value; public AbstractKafkaPushTask(KafkaTaskType taskType) { this.taskType = taskType; } public KafkaTaskType getTaskType() { return taskType; } public Object getValue() { return value; } /** * 需要将消息值保存到这里面,值如何获得由子类自己实心 * * @param value */ public abstract void setValue(Object value); } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/kafka/KafkaTaskType.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.kafka; /** * @author twjitm - [Created on 2018-09-04 21:32] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public enum KafkaTaskType { WORLD_CHAT("word_chat"), OUT_LOGIN("word_chat"); private String typeName; KafkaTaskType(String typeName) { this.typeName = typeName; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/kafka/NettyKafkaConsumerListener.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.kafka; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.springframework.kafka.listener.MessageListener; /** * kafka 消息消费者 * * @author twjitm - [Created on 2018-09-04 16:12] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class NettyKafkaConsumerListener implements MessageListener { @Override public void onMessage(ConsumerRecord consumerRecord) { System.out.println(consumerRecord); consumerRecord.value(); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/listener/StartupServerListener.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.listener; 2 | 3 | 4 | import org.springframework.context.ApplicationListener; 5 | import org.springframework.context.event.ContextRefreshedEvent; 6 | 7 | /** 8 | * Created by 文江 on 2017/9/25. 9 | * 长连接监听器 10 | */ 11 | public class StartupServerListener implements ApplicationListener { 12 | 13 | public void start() { 14 | // RealcomTCPServer.getInItStance().startServer(); 15 | } 16 | 17 | @Override 18 | public void onApplicationEvent(ContextRefreshedEvent evt) { 19 | // if (evt.getApplicationContext().getParent() == null) { 20 | // ClassLoader classLoader=this.getClass().getClassLoader(); 21 | // classLoader.getResource("com.twjitm.common"); 22 | // TwjThreadFactory factory = new TwjThreadFactory(); 23 | // factory.newThread(new Runnable() { 24 | // public void run() { 25 | // bootstrap(); 26 | // } 27 | // }).bootstrap(); 28 | // } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/logic/chat/ChatHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.logic.chat; 2 | 3 | 4 | import com.twjitm.core.common.annotation.MessageCommandAnnotation; 5 | import com.twjitm.core.common.entity.chat.ChatMessage; 6 | import com.twjitm.core.common.enums.MessageComm; 7 | import com.twjitm.core.common.logic.handler.AbstractBaseHandler; 8 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 9 | 10 | public abstract class ChatHandler extends AbstractBaseHandler { 11 | 12 | @MessageCommandAnnotation(messageCmd = MessageComm.PRIVATE_CHAT_MESSAGE) 13 | public AbstractNettyNetProtoBufMessage chatMessage(ChatMessage chatMessage) { 14 | System.out.println("实现代理注解方法了"); 15 | return chatMessageImpl(chatMessage); 16 | } 17 | 18 | 19 | public abstract AbstractNettyNetProtoBufMessage chatMessageImpl(ChatMessage chatMessage); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/logic/chat/Impl/ChatHandlerImpl.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.logic.chat.Impl; 2 | 3 | 4 | import com.twjitm.core.common.entity.chat.ChatMessage; 5 | import com.twjitm.core.common.logic.chat.ChatHandler; 6 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 7 | 8 | public class ChatHandlerImpl extends ChatHandler { 9 | //业务逻辑代码了 10 | public AbstractNettyNetProtoBufMessage chatMessageImpl(ChatMessage chatMessage) { 11 | // chatMessage.getSendUid(); 12 | System.out.println("注解分离消息机制----------"); 13 | System.out.println(chatMessage.getContext()); 14 | ChatMessage message=new ChatMessage(); 15 | message=chatMessage; 16 | message.setContext("hello client"); 17 | return message; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/logic/handler/AbstractBaseHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.logic.handler; 2 | 3 | 4 | import com.twjitm.core.common.annotation.MessageCommandAnnotation; 5 | 6 | import java.lang.reflect.Method; 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | public abstract class AbstractBaseHandler implements BaseHandler { 11 | 12 | public Map handlerMethods; 13 | 14 | public AbstractBaseHandler() { 15 | init(); 16 | } 17 | 18 | public void init() { 19 | handlerMethods = new HashMap<>(); 20 | Method[] methods = this.getClass().getMethods(); 21 | for (Method method : methods) { 22 | if (method.isAnnotationPresent(MessageCommandAnnotation.class)) { 23 | MessageCommandAnnotation messageCommandAnnotation = method.getAnnotation(MessageCommandAnnotation.class); 24 | if (messageCommandAnnotation != null) { 25 | handlerMethods.put(messageCommandAnnotation.messageCmd().commId, method); 26 | } 27 | } 28 | } 29 | 30 | } 31 | 32 | @Override 33 | public Method getMethod(int commId) { 34 | return handlerMethods.get(commId); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/logic/handler/BaseHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.logic.handler; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | public interface BaseHandler { 6 | public Method getMethod(int commId); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/logic/online/Impl/LoginOnLineHandlerImpl.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.logic.online.Impl; 2 | 3 | import com.twjitm.core.common.entity.online.LoginOnlineClientTcpMessage; 4 | import com.twjitm.core.common.enums.MessageAttributeEnum; 5 | import com.twjitm.core.common.logic.online.LoginOnLineHandler; 6 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 7 | import com.twjitm.core.common.netstack.session.NettySession; 8 | import com.twjitm.core.common.netstack.session.tcp.NettyTcpSession; 9 | import com.twjitm.core.common.service.Impl.NettyGamePlayerFindServiceImpl; 10 | import com.twjitm.core.player.entity.GameNettyPlayer; 11 | import com.twjitm.core.spring.SpringLoadServiceImpl; 12 | import com.twjitm.core.spring.SpringServiceManager; 13 | 14 | /** 15 | * @author twjitm - [Created on 2018-08-08 17:38] 16 | * @company https://github.com/twjitm/ 17 | * @jdk java version "1.8.0_77" 18 | */ 19 | public class LoginOnLineHandlerImpl extends LoginOnLineHandler { 20 | @Override 21 | public AbstractNettyNetMessage loginImpl(LoginOnlineClientTcpMessage message) { 22 | //登录游戏简单 23 | 24 | long id = SpringServiceManager.springLoadService.getLongIdGenerator().generateId(); 25 | long playerId = 10086 ; 26 | int token = 10086; 27 | NettyTcpSession session = (NettyTcpSession) message.getAttribute(MessageAttributeEnum.DISPATCH_SESSION); 28 | session.setPlayerId(playerId); 29 | GameNettyPlayer gameNettyPlayer=new GameNettyPlayer(playerId,token,session.getNetTcpMessageSender()); 30 | NettyGamePlayerFindServiceImpl nettyGamePlayerLoopUpService = SpringServiceManager.springLoadService.getNettyGamePlayerLoopUpService(); 31 | nettyGamePlayerLoopUpService.addT(gameNettyPlayer); 32 | AbstractNettyNetMessage responseMessage = SpringServiceManager.springLoadService.getNettyTcpMessageFactory().createCommonResponseMessage((int) session.getSessionId()); 33 | return responseMessage; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/logic/online/LoginOnLineHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.logic.online; 2 | 3 | import com.twjitm.core.common.annotation.MessageCommandAnnotation; 4 | import com.twjitm.core.common.entity.online.LoginOnlineClientTcpMessage; 5 | import com.twjitm.core.common.enums.MessageComm; 6 | import com.twjitm.core.common.logic.handler.AbstractBaseHandler; 7 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 8 | import com.twjitm.core.utils.logs.LoggerUtils; 9 | import org.apache.log4j.Logger; 10 | 11 | /** 12 | * @author twjitm - [Created on 2018-08-08 17:35] 13 | * @company https://github.com/twjitm/ 14 | * @jdk java version "1.8.0_77" 15 | */ 16 | public abstract class LoginOnLineHandler extends AbstractBaseHandler { 17 | Logger logger = LoggerUtils.getLogger(LoginOnLineHandler.class); 18 | 19 | @MessageCommandAnnotation(messageCmd = MessageComm.PLAYER_LOGIN_MESSAGE) 20 | public AbstractNettyNetMessage login(LoginOnlineClientTcpMessage message) { 21 | logger.info("INVOKE HANDLER BEGAN.......loginImpl()"); 22 | return loginImpl(message); 23 | } 24 | 25 | public abstract AbstractNettyNetMessage loginImpl(LoginOnlineClientTcpMessage message); 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/builder/ISessionBuilder.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.builder; 2 | 3 | import com.twjitm.core.common.netstack.session.ISession; 4 | import io.netty.channel.Channel; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-07-26 20:09] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | */ 11 | public interface ISessionBuilder { 12 | 13 | /** 14 | * 绑定session,将netty的{@link Channel} 15 | * 组件和自定义{@link com.twjitm.core.common.netstack.session.NettySession}对象进行绑定 16 | * 17 | * @param channel 18 | * @return 19 | */ 20 | public ISession buildSession(Channel channel); 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/builder/NettyTcpSessionBuilder.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.builder; 2 | 3 | import com.twjitm.core.common.netstack.session.ISession; 4 | import com.twjitm.core.common.netstack.session.tcp.NettyTcpSession; 5 | import io.netty.channel.Channel; 6 | import io.netty.util.AttributeKey; 7 | import org.springframework.stereotype.Service; 8 | 9 | /** 10 | * @author twjitm - [Created on 2018-07-26 20:09] 11 | * @jdk java version "1.8.0_77" 12 | */ 13 | @Service 14 | public class NettyTcpSessionBuilder implements ISessionBuilder { 15 | /** 16 | * 通过netty 提供的属性保存机制,提供在{@link Channel}中保存一些自定义数据的容器。 17 | * {@link AttributeKey} 18 | */ 19 | public static final AttributeKey SESSION_ID = AttributeKey.valueOf("SESSION_ID"); 20 | 21 | @Override 22 | public ISession buildSession(Channel channel) { 23 | NettyTcpSession tcpSession = new NettyTcpSession(channel); 24 | channel.attr(SESSION_ID).set(tcpSession.getSessionId()); 25 | return tcpSession; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/builder/NettyUdpSessionBuilder.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.builder; 2 | 3 | import com.twjitm.core.common.netstack.session.ISession; 4 | import com.twjitm.core.common.netstack.session.udp.NettyUdpSession; 5 | import io.netty.channel.Channel; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * @author twjitm - [Created on 2018-08-09 16:42] 10 | * @company https://github.com/twjitm/ 11 | * @jdk java version "1.8.0_77" 12 | */ 13 | @Service 14 | public class NettyUdpSessionBuilder implements ISessionBuilder { 15 | 16 | @Override 17 | public ISession buildSession(Channel channel) { 18 | return new NettyUdpSession(channel); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/decode/INettyNetProtoBuffToMessageDecoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.decode; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 5 | import io.netty.buffer.ByteBuf; 6 | 7 | /** 8 | * Created by 文江 on 2017/11/16. 9 | * proto基础消息工厂 10 | */ 11 | public interface INettyNetProtoBuffToMessageDecoderFactory { 12 | /** 13 | * handler netty net message 14 | * @param byteBuf 15 | * @return 16 | */ 17 | public AbstractNettyNetProtoBufMessage parseMessage(ByteBuf byteBuf); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/decode/http/INettyNetProtoBuffHttpToMessageDecoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.decode.http; 2 | 3 | import com.twjitm.core.common.netstack.coder.decode.INettyNetProtoBuffToMessageDecoderFactory; 4 | 5 | /** 6 | * Created by 文江 on 2017/11/16. 7 | * http协议编码工厂接口 8 | */ 9 | public interface INettyNetProtoBuffHttpToMessageDecoderFactory extends INettyNetProtoBuffToMessageDecoderFactory { 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/decode/rpc/NettyNetMessageRPCDecoder.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.decode.rpc; import com.twjitm.core.common.service.rpc.serialize.NettyProtoBufRpcSerialize; import com.twjitm.core.spring.SpringServiceManager; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.util.List; /** * @author twjitm - [Created on 2018-08-17 18:37] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class NettyNetMessageRPCDecoder extends ByteToMessageDecoder { private Class> genericClass; public NettyNetMessageRPCDecoder(Class> genericClass) { this.genericClass = genericClass; } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { if (in.readableBytes() < 4) { return; } in.markReaderIndex(); int dataLength = in.readInt(); /*if (dataLength <= 0) { ctx.close(); }*/ if (in.readableBytes() < dataLength) { in.resetReaderIndex(); return; } byte[] data = new byte[dataLength]; in.readBytes(data); NettyProtoBufRpcSerialize serialize = SpringServiceManager.getSpringLoadService().getNettyProtoBufRpcSerialize(); Object obj = serialize.deserialize(data, genericClass); out.add(obj); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/decode/tcp/INettyNetProtoBuffTCPToMessageDecoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.decode.tcp; 2 | 3 | import com.twjitm.core.common.netstack.coder.decode.INettyNetProtoBuffToMessageDecoderFactory; 4 | import org.springframework.stereotype.Service; 5 | 6 | /** 7 | * Created by 文江 on 2017/11/16. 8 | */ 9 | @Service 10 | public interface INettyNetProtoBuffTCPToMessageDecoderFactory extends INettyNetProtoBuffToMessageDecoderFactory { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/decode/tcp/NettyNetProtoBufMessageTCPDecoder.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.decode.tcp; 2 | 3 | import com.twjitm.core.spring.SpringServiceManager; 4 | import com.twjitm.core.utils.logs.LoggerUtils; 5 | import io.netty.buffer.ByteBuf; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.handler.codec.MessageToMessageDecoder; 8 | import io.netty.util.CharsetUtil; 9 | import org.apache.log4j.Logger; 10 | 11 | import java.nio.charset.Charset; 12 | import java.util.List; 13 | 14 | /** 15 | * @author tjwitm 16 | * @date 2017/11/16 17 | */ 18 | public class NettyNetProtoBufMessageTCPDecoder extends MessageToMessageDecoder { 19 | Logger logger = LoggerUtils.getLogger(NettyNetProtoBufMessageTCPDecoder.class); 20 | private final Charset charset; 21 | private INettyNetProtoBuffTCPToMessageDecoderFactory iNettyNetProtoBuffTCPToMessageDecoderFactory; 22 | 23 | public NettyNetProtoBufMessageTCPDecoder() { 24 | this(CharsetUtil.UTF_8); 25 | } 26 | 27 | public NettyNetProtoBufMessageTCPDecoder(Class extends ByteBuf> inboundMessageType, Charset charset, INettyNetProtoBuffTCPToMessageDecoderFactory iNettyNetProtoBuffTCPToMessageDecoerFactory) { 28 | super(inboundMessageType); 29 | this.charset = charset; 30 | this.iNettyNetProtoBuffTCPToMessageDecoderFactory = iNettyNetProtoBuffTCPToMessageDecoerFactory; 31 | } 32 | 33 | public NettyNetProtoBufMessageTCPDecoder(Charset charset) { 34 | if (charset == null) { 35 | throw new NullPointerException("charset"); 36 | } 37 | this.charset = charset; 38 | iNettyNetProtoBuffTCPToMessageDecoderFactory = SpringServiceManager.springLoadService.getNettyNetProtoBuffTCPToMessageDecoderFactory(); 39 | } 40 | 41 | @Override 42 | protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List out) throws Exception { 43 | if (iNettyNetProtoBuffTCPToMessageDecoderFactory == null) { 44 | logger.error("iNettyNetProtoBuffTCPToMessageDecoderFactory is null "); 45 | } else { 46 | out.add(iNettyNetProtoBuffTCPToMessageDecoderFactory.parseMessage(msg)); 47 | 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/decode/udp/INettyNetProtoBuffUDPToMessageDecoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.decode.udp; 2 | 3 | import com.twjitm.core.common.netstack.coder.decode.INettyNetProtoBuffToMessageDecoderFactory; 4 | 5 | /** 6 | * Created by 文江 on 2017/11/16. 7 | */ 8 | public interface INettyNetProtoBuffUDPToMessageDecoderFactory extends INettyNetProtoBuffToMessageDecoderFactory { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/decode/udp/NettyNetProtoBufMessageUDPDecoder.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.decode.udp; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.udp.AbstractNettyNetProtoBufUdpMessage; 5 | import com.twjitm.core.spring.SpringServiceManager; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.channel.socket.DatagramPacket; 8 | import io.netty.handler.codec.MessageToMessageDecoder; 9 | import io.netty.util.CharsetUtil; 10 | 11 | import java.nio.charset.Charset; 12 | import java.util.List; 13 | 14 | /** 15 | * @author twjitm - [Created on 2018-07-30 11:04] 16 | * udp协议解码器 17 | * 18 | * @jdk java version "1.8.0_77" 19 | */ 20 | public class NettyNetProtoBufMessageUDPDecoder extends MessageToMessageDecoder { 21 | private final Charset charset; 22 | private INettyNetProtoBuffUDPToMessageDecoderFactory nettyNetProtoBuffUDPToMessageDecoderFactory; 23 | 24 | public NettyNetProtoBufMessageUDPDecoder() { 25 | this.charset = CharsetUtil.UTF_8; 26 | nettyNetProtoBuffUDPToMessageDecoderFactory = SpringServiceManager.springLoadService.getNettyNetProtoBuffUDPToMessageDecoderFactory(); 27 | } 28 | 29 | public NettyNetProtoBufMessageUDPDecoder(Charset charset) { 30 | this.charset = charset; 31 | nettyNetProtoBuffUDPToMessageDecoderFactory = SpringServiceManager.springLoadService.getNettyNetProtoBuffUDPToMessageDecoderFactory(); 32 | } 33 | 34 | @Override 35 | protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List out) throws Exception { 36 | AbstractNettyNetProtoBufUdpMessage abstractNettyNetProtoBufUdpMessage = (AbstractNettyNetProtoBufUdpMessage) nettyNetProtoBuffUDPToMessageDecoderFactory.parseMessage(msg.content()); 37 | abstractNettyNetProtoBufUdpMessage.setSend(msg.sender()); 38 | out.add(abstractNettyNetProtoBufUdpMessage); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/encode/INettyNetProtoBufMessageEncoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.encode; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 4 | import io.netty.buffer.ByteBuf; 5 | 6 | 7 | public interface INettyNetProtoBufMessageEncoderFactory { 8 | public ByteBuf createByteBuf(AbstractNettyNetProtoBufMessage netMessage) throws Exception; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/encode/http/INettyNetProtoBufHttpMessageEncoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.encode.http; 2 | 3 | import com.twjitm.core.common.netstack.coder.encode.INettyNetProtoBufMessageEncoderFactory; 4 | 5 | /** 6 | * 7 | */ 8 | public interface INettyNetProtoBufHttpMessageEncoderFactory extends INettyNetProtoBufMessageEncoderFactory { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/encode/http/NettyNetProtoBufHttpMessageEncoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.encode.http; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 5 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 6 | import com.twjitm.core.common.netstack.entity.http.NettyNetHttpMessageHead; 7 | import io.netty.buffer.ByteBuf; 8 | import io.netty.buffer.Unpooled; 9 | import org.springframework.stereotype.Service; 10 | 11 | /** 12 | * 13 | */ 14 | @Service 15 | public class NettyNetProtoBufHttpMessageEncoderFactory implements INettyNetProtoBufHttpMessageEncoderFactory { 16 | 17 | @Override 18 | public ByteBuf createByteBuf(AbstractNettyNetProtoBufMessage netMessage) throws Exception { 19 | ByteBuf byteBuf = Unpooled.buffer(256); 20 | //编写head 21 | NettyNetHttpMessageHead netMessageHead = (NettyNetHttpMessageHead) netMessage.getNetMessageHead(); 22 | byteBuf.writeShort(netMessageHead.getHead()); 23 | //长度 24 | byteBuf.writeInt(0); 25 | //设置内容 26 | byteBuf.writeByte(netMessageHead.getVersion()); 27 | byteBuf.writeShort(netMessageHead.getCmd()); 28 | byteBuf.writeInt(netMessageHead.getSerial()); 29 | //设置tocken 30 | byteBuf.writeLong(netMessageHead.getPlayerId()); 31 | byte[] bytes = netMessageHead.getToken().getBytes(); 32 | byteBuf.writeShort(bytes.length); 33 | byteBuf.writeBytes(bytes); 34 | 35 | //编写body 36 | netMessage.encodeNetProtoBufMessageBody(); 37 | NettyNetMessageBody netMessageBody = netMessage.getNetMessageBody(); 38 | byteBuf.writeBytes(netMessageBody.getBytes()); 39 | 40 | //重新设置长度 41 | int skip = 6; //short + int 42 | int length = byteBuf.readableBytes() - skip; 43 | byteBuf.setInt(2, length); 44 | byteBuf.slice(); 45 | return byteBuf; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/encode/rpc/NettyNetMessageRPCEncoder.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.encode.rpc; 2 | 3 | import com.twjitm.core.common.service.rpc.serialize.NettyProtoBufRpcSerialize; 4 | import com.twjitm.core.spring.SpringServiceManager; 5 | import io.netty.buffer.ByteBuf; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.handler.codec.MessageToByteEncoder; 8 | 9 | /** 10 | * Created by IntelliJ IDEA. 11 | * User: 文江 Date: 2018/8/19 Time: 9:55 12 | * https://blog.csdn.net/baidu_23086307 13 | */ 14 | public class NettyNetMessageRPCEncoder extends MessageToByteEncoder { 15 | 16 | private Class> genericClass; 17 | 18 | public NettyNetMessageRPCEncoder(Class> genericClass) { 19 | this.genericClass = genericClass; 20 | } 21 | 22 | @Override 23 | public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) throws Exception { 24 | if (genericClass.isInstance(in)) { 25 | NettyProtoBufRpcSerialize serialize = SpringServiceManager.getSpringLoadService().getNettyProtoBufRpcSerialize(); 26 | byte[] data = serialize.serialize(in); 27 | out.writeInt(data.length); 28 | out.writeBytes(data); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/encode/tcp/INettyNetProtoBufTcpMessageEncoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.encode.tcp; 2 | 3 | import com.twjitm.core.common.netstack.coder.encode.INettyNetProtoBufMessageEncoderFactory; 4 | 5 | /** 6 | * Created by twjitm on 7 | */ 8 | public interface INettyNetProtoBufTcpMessageEncoderFactory extends INettyNetProtoBufMessageEncoderFactory { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/encode/tcp/NettyNetProtoBufMessageTCPEncoder.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.encode.tcp; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 4 | import com.twjitm.core.spring.SpringServiceManager; 5 | import io.netty.buffer.ByteBuf; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.handler.codec.MessageToMessageEncoder; 8 | import io.netty.util.CharsetUtil; 9 | 10 | import java.nio.charset.Charset; 11 | import java.util.List; 12 | 13 | 14 | public class NettyNetProtoBufMessageTCPEncoder extends MessageToMessageEncoder { 15 | 16 | private final Charset charset; 17 | 18 | private INettyNetProtoBufTcpMessageEncoderFactory iNetMessageEncoderFactory; 19 | 20 | public NettyNetProtoBufMessageTCPEncoder() { 21 | this(CharsetUtil.UTF_8); 22 | this.iNetMessageEncoderFactory = SpringServiceManager.springLoadService.getNettyNetProtoBufTcpMessageEncoderFactory(); 23 | } 24 | 25 | public NettyNetProtoBufMessageTCPEncoder(Charset charset) { 26 | if(charset == null) { 27 | throw new NullPointerException("charset"); 28 | } else { 29 | this.charset = charset; 30 | } 31 | } 32 | 33 | @Override 34 | protected void encode(ChannelHandlerContext ctx, AbstractNettyNetProtoBufMessage msg, List out) throws Exception { 35 | ByteBuf netMessageBuf = iNetMessageEncoderFactory.createByteBuf(msg); 36 | out.add(netMessageBuf); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/encode/tcp/NettyNetProtoBufTcpMessageEncoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.encode.tcp; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 5 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 6 | import com.twjitm.core.common.netstack.entity.NettyNetMessageHead; 7 | import io.netty.buffer.ByteBuf; 8 | import io.netty.buffer.Unpooled; 9 | import org.springframework.stereotype.Service; 10 | 11 | 12 | /** 13 | * tcp proto buf 协议编码器工厂,主要完成编码功能 14 | * 15 | * @author twjitm 16 | */ 17 | @Service 18 | public class NettyNetProtoBufTcpMessageEncoderFactory implements INettyNetProtoBufTcpMessageEncoderFactory { 19 | 20 | @Override 21 | public ByteBuf createByteBuf(AbstractNettyNetProtoBufMessage netMessage) throws Exception { 22 | ByteBuf byteBuf = Unpooled.buffer(256); 23 | //编写head 24 | NettyNetMessageHead netMessageHead = netMessage.getNetMessageHead(); 25 | byteBuf.writeShort(netMessageHead.getHead()); 26 | //长度 27 | byteBuf.writeInt(netMessageHead.getLength()); 28 | //设置内容 29 | byteBuf.writeByte(netMessageHead.getVersion()); 30 | //设置消息id 31 | byteBuf.writeShort(netMessageHead.getCmd()); 32 | //设置系列号 33 | byteBuf.writeInt(netMessageHead.getSerial()); 34 | //编写body 35 | netMessage.encodeNetProtoBufMessageBody(); 36 | NettyNetMessageBody netMessageBody = netMessage.getNetMessageBody(); 37 | byteBuf.writeBytes(netMessageBody.getBytes()); 38 | 39 | //重新设置长度 40 | int skip = 6; 41 | int length = byteBuf.readableBytes() - skip; 42 | byteBuf.setInt(2, length); 43 | //!!!!!!!注意此方法不能调用retain() 44 | byteBuf.slice(); 45 | return byteBuf; 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/encode/udp/INettyNetProtoBufUdpMessageEncoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.encode.udp; 2 | 3 | import com.twjitm.core.common.netstack.coder.encode.INettyNetProtoBufMessageEncoderFactory; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-07-30 10:45] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public interface INettyNetProtoBufUdpMessageEncoderFactory extends INettyNetProtoBufMessageEncoderFactory { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/encode/udp/NettyNetProtoBufMessageUDPEncoder.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.encode.udp; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 4 | import com.twjitm.core.common.netstack.entity.udp.AbstractNettyNetProtoBufUdpMessage; 5 | import com.twjitm.core.spring.SpringServiceManager; 6 | import io.netty.buffer.ByteBuf; 7 | import io.netty.channel.ChannelHandlerContext; 8 | import io.netty.channel.socket.DatagramPacket; 9 | import io.netty.handler.codec.MessageToMessageEncoder; 10 | import io.netty.util.CharsetUtil; 11 | 12 | import java.nio.charset.Charset; 13 | import java.util.List; 14 | 15 | /** 16 | * @author twjitm - [Created on 2018-07-30 10:46] 17 | * UDP协议编码器 18 | * @jdk java version "1.8.0_77" 19 | */ 20 | public class NettyNetProtoBufMessageUDPEncoder extends MessageToMessageEncoder { 21 | 22 | private final Charset charset; 23 | private INettyNetProtoBufUdpMessageEncoderFactory nettyNetProtoBufUdpMessageEncoderFactory; 24 | 25 | public NettyNetProtoBufMessageUDPEncoder() { 26 | this.charset = CharsetUtil.UTF_8; 27 | this.nettyNetProtoBufUdpMessageEncoderFactory = SpringServiceManager.springLoadService.getNettyNetProtoBufUdpMessageEncoderFactory(); 28 | } 29 | public NettyNetProtoBufMessageUDPEncoder(Charset charset) { 30 | if (charset == null) { 31 | throw new NullPointerException(); 32 | } 33 | this.charset = charset; 34 | this.nettyNetProtoBufUdpMessageEncoderFactory = SpringServiceManager.springLoadService.getNettyNetProtoBufUdpMessageEncoderFactory(); 35 | } 36 | 37 | @Override 38 | protected void encode(ChannelHandlerContext ctx, AbstractNettyNetProtoBufUdpMessage msg, List out) throws Exception { 39 | ByteBuf byteBuf = nettyNetProtoBufUdpMessageEncoderFactory.createByteBuf(msg); 40 | out.add(new DatagramPacket(byteBuf, msg.getReceive())); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/coder/encode/udp/NettyNetProtoBufUdpMessageEncoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.coder.encode.udp; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 4 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 5 | import com.twjitm.core.common.netstack.entity.udp.NettyUDPMessageHead; 6 | import io.netty.buffer.ByteBuf; 7 | import io.netty.buffer.Unpooled; 8 | import org.springframework.stereotype.Service; 9 | 10 | /** 11 | * @author twjitm - [Created on 2018-07-30 10:46] 12 | * 13 | * UPD协议编码工厂 14 | * @jdk java version "1.8.0_77" 15 | */ 16 | @Service 17 | public class NettyNetProtoBufUdpMessageEncoderFactory implements INettyNetProtoBufUdpMessageEncoderFactory { 18 | @Override 19 | public ByteBuf createByteBuf(AbstractNettyNetProtoBufMessage netMessage) throws Exception { 20 | ByteBuf byteBuf = Unpooled.buffer(256); 21 | //编写head 22 | NettyUDPMessageHead netMessageHead = (NettyUDPMessageHead) netMessage.getNetMessageHead(); 23 | byteBuf.writeShort(netMessageHead.getHead()); 24 | //长度 25 | byteBuf.writeInt(0); 26 | //设置内容 27 | byteBuf.writeByte(netMessageHead.getVersion()); 28 | byteBuf.writeShort(netMessageHead.getCmd()); 29 | byteBuf.writeInt(netMessageHead.getSerial()); 30 | //设置tockent 31 | byteBuf.writeLong(netMessageHead.getPlayerId()); 32 | byteBuf.writeInt(netMessageHead.getTocken()); 33 | 34 | //编写body 35 | netMessage.encodeNetProtoBufMessageBody(); 36 | NettyNetMessageBody netMessageBody = netMessage.getNetMessageBody(); 37 | byteBuf.writeBytes(netMessageBody.getBytes()); 38 | 39 | //重新设置长度 40 | int skip = 6; 41 | int length = byteBuf.readableBytes() - skip; 42 | byteBuf.setInt(2, length); 43 | byteBuf.slice(); 44 | return byteBuf; 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/AbstractNettyNetMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity; 2 | 3 | import java.util.concurrent.ConcurrentHashMap; 4 | 5 | /** 6 | * Created by 文江 on 2017/11/15. 7 | */ 8 | public abstract class AbstractNettyNetMessage implements INettyMessage { 9 | public NettyNetMessageHead nettyNetMessageHead; 10 | public NettyNetMessageBody nettyNetMessageBody; 11 | /** 12 | * 增加默认属性(附带逻辑调用需要的属性) 13 | */ 14 | private final ConcurrentHashMap attributes = new ConcurrentHashMap(3); 15 | 16 | 17 | public NettyNetMessageHead getNettyNetMessageHead() { 18 | return nettyNetMessageHead; 19 | } 20 | 21 | public void setNettyNetMessageHead(NettyNetMessageHead nettyNetMessageHead) { 22 | this.nettyNetMessageHead = nettyNetMessageHead; 23 | } 24 | 25 | public NettyNetMessageBody getNettyNetMessageBody() { 26 | return nettyNetMessageBody; 27 | } 28 | 29 | public void setNettyNetMessageBody(NettyNetMessageBody nettyNetMessageBody) { 30 | this.nettyNetMessageBody = nettyNetMessageBody; 31 | } 32 | 33 | public void setAttribute(Object key,Object value){ 34 | attributes.put(key,value); 35 | } 36 | 37 | public Object getAttribute(Object key){ 38 | return attributes.get(key); 39 | } 40 | public void remove(Object key){ 41 | attributes.remove(key); 42 | } 43 | 44 | @Override 45 | public String toString() { 46 | return "AbstractNettyNetMessage{" + 47 | "nettyNetMessageHead=" + nettyNetMessageHead + 48 | ", nettyNetMessageBody=" + nettyNetMessageBody + 49 | ", attributes=" + attributes + 50 | '}'; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/AbstractNettyNetProtoBufMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity; 2 | 3 | import com.twjitm.core.common.annotation.MessageCommandAnnotation; 4 | import io.netty.handler.codec.CodecException; 5 | 6 | 7 | /** 8 | * Created by twjitm on 2017/11/15. 9 | * 基础protobuf协议消息 10 | */ 11 | public abstract class AbstractNettyNetProtoBufMessage extends AbstractNettyNetMessage { 12 | 13 | public AbstractNettyNetProtoBufMessage() { 14 | setNettyNetMessageHead(new NettyNetMessageHead()); 15 | setNettyNetMessageBody(new NettyNetMessageBody()); 16 | } 17 | 18 | @Override 19 | public NettyNetMessageHead getNetMessageHead() { 20 | return getNettyNetMessageHead(); 21 | } 22 | 23 | @Override 24 | public NettyNetMessageBody getNetMessageBody() { 25 | return getNettyNetMessageBody(); 26 | } 27 | 28 | protected void initHeadCommId() { 29 | MessageCommandAnnotation messageCommandAnnotation = this.getClass().getAnnotation(MessageCommandAnnotation.class); 30 | if (messageCommandAnnotation != null) { 31 | getNetMessageHead().setCmd((short) messageCommandAnnotation.messageCmd().commId); 32 | } 33 | } 34 | 35 | /** 36 | * 释放message的body 37 | */ 38 | public void releaseMessageBody() throws CodecException, Exception { 39 | getNetMessageBody().setBytes(null); 40 | } 41 | 42 | public abstract void release() throws CodecException; 43 | 44 | public abstract void encodeNetProtoBufMessageBody() throws CodecException, Exception; 45 | 46 | public abstract void decoderNetProtoBufMessageBody() throws CodecException, Exception; 47 | 48 | public void setSerial(int serial) { 49 | getNetMessageHead().setSerial(serial); 50 | } 51 | 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/INettyMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 5 | import com.twjitm.core.common.netstack.entity.NettyNetMessageHead; 6 | 7 | /** 8 | * Created by 文江 on 2017/11/15. 9 | * 基础协议 10 | */ 11 | public interface INettyMessage { 12 | public NettyNetMessageHead getNetMessageHead(); 13 | public NettyNetMessageBody getNetMessageBody(); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/NettyNetMessageBody.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity; 2 | 3 | /** 4 | * Created by 文江 on 2017/11/15. 5 | */ 6 | public class NettyNetMessageBody { 7 | /** 8 | * 存储数据 9 | */ 10 | private byte[] bytes; 11 | 12 | public byte[] getBytes() { 13 | return bytes; 14 | } 15 | 16 | public void setBytes(byte[] bytes) { 17 | this.bytes = bytes; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/NettyNetMessageHead.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity; 2 | 3 | /** 4 | * Created by 文江 on 2017/11/15. 5 | */ 6 | public class NettyNetMessageHead { 7 | 8 | public static final short MESSAGE_HEADER_FLAG = 0x2425; 9 | 10 | /** 11 | * 魔法头 12 | */ 13 | private short head; 14 | /** 15 | * 版本号 16 | */ 17 | private byte version; 18 | /** 19 | * 长度 20 | */ 21 | private int length; 22 | /** 23 | * 命令 24 | */ 25 | private short cmd; 26 | /** 27 | * 序列号 28 | */ 29 | private int serial; 30 | 31 | public NettyNetMessageHead() { 32 | this.head = MESSAGE_HEADER_FLAG; 33 | } 34 | 35 | public short getHead() { 36 | return head; 37 | } 38 | 39 | public void setHead(short head) { 40 | this.head = head; 41 | } 42 | 43 | public byte getVersion() { 44 | return version; 45 | } 46 | 47 | public void setVersion(byte version) { 48 | this.version = version; 49 | } 50 | 51 | public int getLength() { 52 | return length; 53 | } 54 | 55 | public void setLength(int length) { 56 | this.length = length; 57 | } 58 | 59 | public short getCmd() { 60 | return cmd; 61 | } 62 | 63 | public void setCmd(short cmd) { 64 | this.cmd = cmd; 65 | } 66 | 67 | public int getSerial() { 68 | return serial; 69 | } 70 | 71 | public void setSerial(int serial) { 72 | this.serial = serial; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/NettyNetProtoBufMessageBody.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity; 2 | 3 | import com.google.protobuf.AbstractMessage; 4 | 5 | /** 6 | * Created by 文江 on 2017/11/15. 7 | */ 8 | public class NettyNetProtoBufMessageBody extends NettyNetMessageBody{ 9 | //将字节读取为protobuf的抽象对象 10 | private AbstractMessage abstractMessage; 11 | 12 | public AbstractMessage getAbstractMessage() { 13 | return abstractMessage; 14 | } 15 | 16 | public void setAbstractMessage(AbstractMessage abstractMessage) { 17 | this.abstractMessage = abstractMessage; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/http/AbstractNettyNetProtoBufHttpMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.http; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 5 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 6 | 7 | /** 8 | * Created by 文江 on 2017/11/16. 9 | * 抽象http请求消息 10 | */ 11 | public abstract class AbstractNettyNetProtoBufHttpMessage extends AbstractNettyNetProtoBufMessage { 12 | public AbstractNettyNetProtoBufHttpMessage(){ 13 | super(); 14 | setNettyNetMessageHead(new NettyNetHttpMessageHead()); 15 | setNettyNetMessageBody(new NettyNetMessageBody()); 16 | initHeadCommId(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/http/NettyNetHttpMessageHead.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.http; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.NettyNetMessageHead; 5 | 6 | /** 7 | * Created by 文江 on 2017/11/16. 8 | * http协议头 9 | */ 10 | public class NettyNetHttpMessageHead extends NettyNetMessageHead { 11 | private long playerId; 12 | private String token = ""; 13 | 14 | public long getPlayerId() { 15 | return playerId; 16 | } 17 | 18 | public void setPlayerId(long playerId) { 19 | this.playerId = playerId; 20 | } 21 | 22 | public String getToken() { 23 | return token; 24 | } 25 | 26 | public void setToken(String token) { 27 | this.token = token; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/rpc/NettyRpcRequestMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.rpc; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: 文江 Date: 2018/8/19 Time: 10:10 6 | * https://blog.csdn.net/baidu_23086307 7 | */ 8 | public class NettyRpcRequestMessage { 9 | /** 10 | * 请求id 11 | */ 12 | private String requestId; 13 | /** 14 | * class 名 15 | */ 16 | private String className; 17 | /** 18 | * 方法名 19 | */ 20 | private String methodName; 21 | /** 22 | * 请求参数类型 23 | */ 24 | private Class>[] parameterTypes; 25 | /** 26 | * 请求参数 27 | */ 28 | private Object[] parameters; 29 | 30 | public String getRequestId() { 31 | return requestId; 32 | } 33 | 34 | public void setRequestId(String requestId) { 35 | this.requestId = requestId; 36 | } 37 | 38 | public String getClassName() { 39 | return className; 40 | } 41 | 42 | public void setClassName(String className) { 43 | this.className = className; 44 | } 45 | 46 | public String getMethodName() { 47 | return methodName; 48 | } 49 | 50 | public void setMethodName(String methodName) { 51 | this.methodName = methodName; 52 | } 53 | 54 | public Class>[] getParameterTypes() { 55 | return parameterTypes; 56 | } 57 | 58 | public void setParameterTypes(Class>[] parameterTypes) { 59 | this.parameterTypes = parameterTypes; 60 | } 61 | 62 | public Object[] getParameters() { 63 | return parameters; 64 | } 65 | 66 | public void setParameters(Object[] parameters) { 67 | this.parameters = parameters; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/rpc/NettyRpcResponseMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.rpc; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: 文江 Date: 2018/8/19 Time: 10:15 6 | * https://blog.csdn.net/baidu_23086307 7 | */ 8 | public class NettyRpcResponseMessage { 9 | /** 10 | * 请求id 11 | */ 12 | private String requestId; 13 | /** 14 | * 错误码 15 | */ 16 | private String error; 17 | /** 18 | * 返回值 19 | */ 20 | private Object result; 21 | 22 | public String getRequestId() { 23 | return requestId; 24 | } 25 | 26 | public String getError() { 27 | return error; 28 | } 29 | 30 | public Object getResult() { 31 | return result; 32 | } 33 | 34 | public void setRequestId(String requestId) { 35 | this.requestId = requestId; 36 | } 37 | 38 | public void setError(String error) { 39 | this.error = error; 40 | } 41 | 42 | public void setResult(Object result) { 43 | this.result = result; 44 | } 45 | public boolean isError() { 46 | return error != null; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/tcp/AbstractNettyNetProtoBufTcpMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.tcp; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 5 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 6 | import com.twjitm.core.common.netstack.entity.NettyNetMessageHead; 7 | 8 | /** 9 | * Created by 文江 on 2017/11/15. 10 | */ 11 | public abstract class AbstractNettyNetProtoBufTcpMessage extends AbstractNettyNetProtoBufMessage { 12 | public AbstractNettyNetProtoBufTcpMessage() { 13 | super(); 14 | setNettyNetMessageHead(new NettyNetMessageHead()); 15 | setNettyNetMessageBody(new NettyNetMessageBody()); 16 | initHeadCommId(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/tcp/NettyTCPMessageBody.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.tcp; 2 | 3 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 4 | 5 | /** 6 | * Created by 文江 on 2017/11/15. 7 | */ 8 | public class NettyTCPMessageBody extends NettyNetMessageBody { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/tcp/NettyTCPMessageHead.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.tcp; 2 | 3 | import com.twjitm.core.common.netstack.entity.NettyNetMessageHead; 4 | 5 | /** 6 | * Created by 文江 on 2017/11/15. 7 | */ 8 | public class NettyTCPMessageHead extends NettyNetMessageHead { 9 | public NettyTCPMessageHead() { 10 | super(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/udp/AbstractNettyNetProtoBufUdpMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.udp; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 5 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 6 | 7 | import java.net.InetSocketAddress; 8 | 9 | /** 10 | * Created by twjtim on 2017/2/16. 11 | * 抽象的udp消息 12 | */ 13 | public abstract class AbstractNettyNetProtoBufUdpMessage extends AbstractNettyNetProtoBufMessage { 14 | /** 15 | * 发送方 16 | */ 17 | private InetSocketAddress send; 18 | /** 19 | * 接收方 20 | */ 21 | private InetSocketAddress receive; 22 | 23 | 24 | public InetSocketAddress getSend() { 25 | return send; 26 | } 27 | 28 | public void setSend(InetSocketAddress send) { 29 | this.send = send; 30 | } 31 | 32 | public InetSocketAddress getReceive() { 33 | return receive; 34 | } 35 | 36 | public void setReceive(InetSocketAddress receive) { 37 | this.receive = receive; 38 | } 39 | 40 | public AbstractNettyNetProtoBufUdpMessage(){ 41 | super(); 42 | setNettyNetMessageHead(new NettyUDPMessageHead()); 43 | setNettyNetMessageBody(new NettyNetMessageBody()); 44 | initHeadCommId(); 45 | } 46 | 47 | public void setPlayerId(long playerId) { 48 | NettyUDPMessageHead netUdpMessageHead = (NettyUDPMessageHead) getNetMessageHead(); 49 | netUdpMessageHead.setPlayerId(playerId); 50 | } 51 | 52 | public void setTocken(int tocken){ 53 | NettyUDPMessageHead netUdpMessageHead = (NettyUDPMessageHead) getNetMessageHead(); 54 | netUdpMessageHead.setTocken(tocken); 55 | } 56 | 57 | public long getPlayerId(){ 58 | NettyUDPMessageHead netUdpMessageHead = (NettyUDPMessageHead) getNetMessageHead(); 59 | return netUdpMessageHead.getPlayerId(); 60 | } 61 | 62 | public int getTocken(){ 63 | NettyUDPMessageHead netUdpMessageHead = (NettyUDPMessageHead) getNetMessageHead(); 64 | return netUdpMessageHead.getTocken(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/udp/NettyUDPMessageHead.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.udp; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.NettyNetMessageHead; 5 | 6 | /** 7 | * Created by 文江 on 2017/11/15. 8 | */ 9 | public class NettyUDPMessageHead extends NettyNetMessageHead { 10 | private long playerId; 11 | private int tocken; 12 | 13 | public long getPlayerId() { 14 | return playerId; 15 | } 16 | 17 | public void setPlayerId(long playerId) { 18 | this.playerId = playerId; 19 | } 20 | 21 | public int getTocken() { 22 | return tocken; 23 | } 24 | 25 | public void setTocken(int tocken) { 26 | this.tocken = tocken; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/udp/NettyUDpMessageBody.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.udp; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 5 | 6 | /** 7 | * Created by 文江 on 2017/11/15. 8 | */ 9 | public class NettyUDpMessageBody extends NettyNetMessageBody { 10 | private long playerId; 11 | private int tocken; 12 | 13 | public long getPlayerId() { 14 | return playerId; 15 | } 16 | 17 | public void setPlayerId(long playerId) { 18 | this.playerId = playerId; 19 | } 20 | 21 | public int getTocken() { 22 | return tocken; 23 | } 24 | 25 | public void setTocken(int tocken) { 26 | this.tocken = tocken; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/pipeline/INettyServerPipeLine.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.pipeline; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import io.netty.channel.Channel; 5 | 6 | /** 7 | * 管道消息分发器。 管道消息分发器,主要是讲tcp消息或者rpc消息,udp消息以及http消息 8 | * 进行分发,由实现类自己完成实现, 9 | * 10 | * @author twjitm - [Created on 2018-08-02 20:39] 11 | * @company https://github.com/twjitm/ 12 | * @jdk java version "1.8.0_77" 13 | */ 14 | public interface INettyServerPipeLine { 15 | /** 16 | * 分发器 17 | * 18 | * @param channel 19 | * @param message 20 | */ 21 | void dispatch(Channel channel, AbstractNettyNetMessage message); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/sender/INetMessageSender.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.sender; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-07-24 16:23] 7 | * 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public interface INetMessageSender { 11 | 12 | /** 13 | * 14 | * 15 | * @param abstractNettyNetMessage 16 | * @return 17 | */ 18 | public boolean sendMessage(AbstractNettyNetMessage abstractNettyNetMessage); 19 | 20 | /** 21 | * 22 | */ 23 | public void close(); 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/sender/NettyNetTcpMessageSender.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.sender; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import com.twjitm.core.common.netstack.session.NettySession; 5 | import com.twjitm.core.utils.logs.LoggerUtils; 6 | import io.netty.channel.Channel; 7 | import org.apache.log4j.Logger; 8 | 9 | /** 10 | * @author twjitm - [Created on 2018-07-24 16:32] 11 | * @jdk java version "1.8.0_77" 12 | * TCP消息发送器 13 | */ 14 | public class NettyNetTcpMessageSender implements INetMessageSender { 15 | private final NettySession nettySession; 16 | private Logger logger = LoggerUtils.getLogger(this.getClass()); 17 | 18 | public NettyNetTcpMessageSender(NettySession nettySession) { 19 | this.nettySession = nettySession; 20 | } 21 | 22 | @Override 23 | public boolean sendMessage(AbstractNettyNetMessage abstractNettyNetMessage) { 24 | try { 25 | nettySession.write(abstractNettyNetMessage); 26 | } catch (Exception e) { 27 | e.printStackTrace(); 28 | logger.error(e.toString()); 29 | } 30 | return true; 31 | } 32 | 33 | @Override 34 | public void close() { 35 | Channel channel = nettySession.channel; 36 | if (channel.isActive()) { 37 | channel.close(); 38 | } else { 39 | channel.close(); 40 | 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/sender/NettyNetUdpMessageSender.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.sender; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import com.twjitm.core.common.netstack.session.NettySession; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-08-09 16:35] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | * udp协议消息发送器 11 | */ 12 | public class NettyNetUdpMessageSender implements INetMessageSender { 13 | private final NettySession nettySession; 14 | 15 | public NettyNetUdpMessageSender(NettySession nettySession) { 16 | this.nettySession = nettySession; 17 | } 18 | 19 | 20 | @Override 21 | public boolean sendMessage(AbstractNettyNetMessage abstractNettyNetMessage) { 22 | try { 23 | nettySession.write(abstractNettyNetMessage); 24 | } catch (Exception e) { 25 | e.printStackTrace(); 26 | return false; 27 | } 28 | return true; 29 | } 30 | 31 | @Override 32 | public void close() { 33 | nettySession.channel.close(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/session/ISession.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.session; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-07-24 15:55] 7 | * @jdk java version "1.8.0_77"\ 8 | * session��ҵ���� 9 | */ 10 | public interface ISession { 11 | /** 12 | * �жϵ�ǰ�Ự�Ƿ�������״̬ 13 | * 14 | * @return 15 | */ 16 | public boolean isConnected(); 17 | 18 | /** 19 | * @param msg 20 | */ 21 | public void write(AbstractNettyNetMessage msg) throws Exception; 22 | 23 | /** 24 | * 25 | */ 26 | public void close(boolean immediately); 27 | 28 | /** 29 | * �����쳣ʱ�Ƿ�ر����� 30 | * 31 | * @return 32 | */ 33 | public boolean closeOnException(); 34 | 35 | public void write(byte[] msg) throws Exception; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/session/NettySession.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.session; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import io.netty.channel.Channel; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-07-24 15:56] 8 | * @jdk java version "1.8.0_77" 9 | * 自定义session 10 | */ 11 | public abstract class NettySession implements ISession { 12 | public volatile Channel channel; 13 | private long playerId; 14 | 15 | 16 | public NettySession(Channel channel) { 17 | this.channel = channel; 18 | } 19 | 20 | @Override 21 | public boolean isConnected() { 22 | if (channel != null) { 23 | return channel.isActive(); 24 | } 25 | return false; 26 | } 27 | 28 | @Override 29 | public void write(AbstractNettyNetMessage msg) throws Exception { 30 | if (msg != null) { 31 | try { 32 | //防止客户端被重置 33 | if (channel.isActive()) { 34 | channel.writeAndFlush(msg); 35 | } 36 | } catch (Exception e) { 37 | throw new Exception(); 38 | } 39 | 40 | } 41 | } 42 | 43 | @Override 44 | public void close(boolean immediately) { 45 | if (channel != null) { 46 | channel.close(); 47 | } 48 | } 49 | 50 | @Override 51 | public boolean closeOnException() { 52 | return false; 53 | } 54 | 55 | @Override 56 | public void write(byte[] msg) throws Exception { 57 | if (channel != null) { 58 | try { 59 | channel.writeAndFlush(msg); 60 | } catch (Exception e) { 61 | throw new Exception(e); 62 | } 63 | } 64 | } 65 | 66 | public long getPlayerId() { 67 | return playerId; 68 | } 69 | 70 | public void setPlayerId(long playerId) { 71 | this.playerId = playerId; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/session/udp/NettyUdpSession.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.session.udp; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import com.twjitm.core.common.netstack.sender.NettyNetUdpMessageSender; 5 | import com.twjitm.core.common.netstack.session.NettySession; 6 | import io.netty.channel.Channel; 7 | 8 | /** 9 | * @author twjitm - [Created on 2018-07-24 15:59] 10 | * @company https://github.com/twjitm/ 11 | * @jdk java version "1.8.0_77" 12 | */ 13 | public class NettyUdpSession extends NettySession { 14 | private NettyNetUdpMessageSender udpMessageSender; 15 | 16 | public NettyUdpSession(Channel channel) { 17 | super(channel); 18 | this.udpMessageSender = new NettyNetUdpMessageSender(this); 19 | } 20 | 21 | @Override 22 | public void write(AbstractNettyNetMessage msg) throws Exception { 23 | if (msg != null) { 24 | if (channel.isActive()) { 25 | channel.writeAndFlush(msg); 26 | } 27 | 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/process/IMessageProcessor.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.process; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import com.twjitm.core.common.netstack.entity.tcp.AbstractNettyNetProtoBufTcpMessage; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-08-06 20:43] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | */ 11 | public interface IMessageProcessor { 12 | /** 13 | * 启动消息处理器 14 | */ 15 | public void startup(); 16 | 17 | /** 18 | * 停止消息处理器 19 | */ 20 | public void shutdown(); 21 | 22 | /** 23 | * 向消息队列投递消息 24 | * 25 | * @param msg 26 | */ 27 | public void put(AbstractNettyNetMessage msg); 28 | 29 | /** 30 | * 判断队列是否已经达到上限了 31 | * @return 32 | */ 33 | public boolean isFull(); 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/process/tcp/INettyTcpNetProtoMessageProcess.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.process.tcp; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-07-24 15:46] 5 | * @jdk java version "1.8.0_77" 6 | */ 7 | 8 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 9 | 10 | /** 11 | * 12 | */ 13 | public interface INettyTcpNetProtoMessageProcess { 14 | public void processNetMessage(); 15 | public void addNetMessage(AbstractNettyNetMessage abstractNettyNetMessage); 16 | public void close(); 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/process/tcp/ITcpMessageProcessor.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.process.tcp; 2 | 3 | import com.twjitm.core.common.process.IMessageProcessor; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-08-06 20:44] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public interface ITcpMessageProcessor extends IMessageProcessor { 11 | public void putDirectTcpMessage(); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/process/udp/NettyUdpNetProtoMessageProcessor.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.process.udp; 2 | 3 | import com.twjitm.core.common.config.global.GlobalConstants; 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 5 | import com.twjitm.core.common.process.IMessageProcessor; 6 | import com.twjitm.core.utils.logs.LoggerUtils; 7 | import org.apache.log4j.Logger; 8 | 9 | /** 10 | * @author twjitm - [Created on 2018-08-08 15:06] 11 | * @company https://github.com/twjitm/ 12 | * @jdk java version "1.8.0_77" 13 | * udp协议消息处理的一种方式:生产者-----消费者模式 14 | */ 15 | public class NettyUdpNetProtoMessageProcessor implements IMessageProcessor { 16 | Logger logger = LoggerUtils.getLogger(NettyUdpNetProtoMessageProcessor.class); 17 | /** 18 | * 消息处理:服务器系统消息 19 | */ 20 | private IMessageProcessor mainMessageProcessor; 21 | 22 | 23 | public NettyUdpNetProtoMessageProcessor(IMessageProcessor mainMessageProcessor) { 24 | this.mainMessageProcessor = mainMessageProcessor; 25 | } 26 | 27 | @Override 28 | public void startup() { 29 | this.mainMessageProcessor.startup(); 30 | } 31 | 32 | @Override 33 | public void shutdown() { 34 | this.mainMessageProcessor.shutdown(); 35 | } 36 | 37 | /** 38 | * 服务器消息选择处理, 39 | * 玩家消息直接处理 40 | * 41 | * @param msg 42 | */ 43 | @Override 44 | public void put(AbstractNettyNetMessage msg) { 45 | if (!GlobalConstants.GameServiceRuntime.IS_OPEN) { 46 | return; 47 | } 48 | logger.info("放入消息执行队列"+msg.toString()); 49 | this.mainMessageProcessor.put(msg); 50 | } 51 | 52 | @Override 53 | public boolean isFull() { 54 | return this.mainMessageProcessor.isFull(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/ILongId.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-08-08 13:54] 5 | * @company https://github.com/twjitm/ 6 | * @jdk java version "1.8.0_77" 7 | */ 8 | public interface ILongId { 9 | public long getLongId(); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/INettyChannleOperationService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service; 2 | 3 | import com.twjitm.core.common.netstack.session.ISession; 4 | import com.twjitm.core.common.netstack.session.tcp.NettyTcpSession; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-07-26 20:37] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | */ 11 | public interface INettyChannleOperationService { 12 | 13 | public ISession findNettySession(long sessionId); 14 | 15 | public boolean addNettySession(NettyTcpSession session); 16 | 17 | public void removeNettySession(long session); 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/INettyLongFindService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-08-08 14:01] 5 | * @company https://github.com/twjitm/ 6 | * @jdk java version "1.8.0_77" 7 | */ 8 | public interface INettyLongFindService { 9 | /** 10 | * 查找 11 | * @param id 12 | * @return 13 | */ 14 | public T findT(long id); 15 | 16 | /** 17 | * 增加 18 | * @param t 19 | */ 20 | public void addT(T t); 21 | 22 | /** 23 | * 移除 24 | * @param t 25 | * @return 26 | */ 27 | public T removeT(T t); 28 | 29 | /** 30 | * 清除所有 31 | */ 32 | public void clear(); 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/IService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-07-26 20:30] 5 | * @company https://github.com/twjitm/ 6 | * @jdk java version "1.8.0_77" 7 | */ 8 | public interface IService { 9 | public String getId(); 10 | 11 | public void startup() throws Exception; 12 | 13 | public void shutdown() throws Exception; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/Impl/AbstractNettyGamePlayerFindService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.Impl; 2 | 3 | import com.twjitm.core.common.service.ILongId; 4 | import com.twjitm.core.common.service.INettyLongFindService; 5 | import com.twjitm.core.utils.logs.LoggerUtils; 6 | import org.apache.log4j.Logger; 7 | 8 | import java.util.concurrent.ConcurrentHashMap; 9 | 10 | /** 11 | * 维护本地在线玩家集和服务 12 | * 13 | * @author twjitm - [Created on 2018-08-08 14:06] 14 | * @company https://github.com/twjitm/ 15 | * @jdk java version "1.8.0_77" 16 | */ 17 | public abstract class AbstractNettyGamePlayerFindService implements INettyLongFindService { 18 | private Logger logger = LoggerUtils.getLogger(AbstractNettyGamePlayerFindService.class); 19 | private volatile ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<>(); 20 | 21 | @Override 22 | public T findT(long id) { 23 | if (logger.isTraceEnabled()) { 24 | logger.info("NETTY GAME FIND ID =" + id); 25 | } 26 | return concurrentHashMap.get(id); 27 | } 28 | 29 | @Override 30 | public void addT(T t) { 31 | if (logger.isTraceEnabled()) { 32 | logger.info("NETTY GAME ADD ID =" + t.getClass().getSimpleName() + "ID IS" + t.getLongId()); 33 | } 34 | concurrentHashMap.put(t.getLongId(), t); 35 | } 36 | 37 | @Override 38 | public T removeT(T t) { 39 | if (logger.isTraceEnabled()) { 40 | logger.info("NETTY GAME REMOVE ID =" + t.getClass().getSimpleName() + "ID IS" + t.getLongId()); 41 | } 42 | return concurrentHashMap.remove(t.getLongId()); 43 | } 44 | 45 | @Override 46 | public void clear() { 47 | if (logger.isTraceEnabled()) { 48 | logger.info("NETTY GAME CLEAR ALL"); 49 | } 50 | concurrentHashMap.clear(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/Impl/NettyGamePlayerFindServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.Impl; 2 | 3 | import com.twjitm.core.player.entity.GameNettyPlayer; 4 | import org.springframework.stereotype.Service; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-08-08 14:04] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | */ 11 | @Service 12 | public class NettyGamePlayerFindServiceImpl extends AbstractNettyGamePlayerFindService { 13 | 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/Impl/NettyGameServiceConfigServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.Impl; 2 | 3 | import com.twjitm.core.common.service.IService; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-08-16 11:07] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public class NettyGameServiceConfigServiceImpl implements IService { 11 | @Override 12 | public String getId() { 13 | return ""; 14 | } 15 | 16 | @Override 17 | public void startup() throws Exception { 18 | 19 | 20 | 21 | } 22 | 23 | @Override 24 | public void shutdown() throws Exception { 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/http/AsyncNettyHttpHandlerService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.http; 2 | 3 | import com.twjitm.core.common.config.global.GlobalConstants; 4 | import com.twjitm.core.common.service.IService; 5 | import io.netty.util.concurrent.DefaultEventExecutorGroup; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * 10 | * 当业务代码中存在对EventLoop线程阻塞的时候,ChannelPipeline 11 | * 有一些能接收一个EventExecutorGroup的add()方法,如果一个事件 12 | * 被专递给自定义的一个EventExecutorGroup,他将会包含在这个EventExecutorGroup 13 | * 中的某个EventExecutor所处理,从而被Channel本身的EventLoop移除,对于这种用法 14 | * Netty提供了一个种叫做{@link io.netty.util.concurrent.DefaultEventExecutorGroup}的实现 15 | * 其实也是本类主要的一个核心API, 16 | * @author twjitm - [Created on 2018-08-16 12:17] 17 | * @company https://github.com/twjitm/ 18 | * @jdk java version "1.8.0_77" 19 | */ 20 | @Service 21 | public class AsyncNettyHttpHandlerService implements IService { 22 | private DefaultEventExecutorGroup defaultEventExecutorGroup; 23 | 24 | 25 | @Override 26 | public String getId() { 27 | return DefaultEventExecutorGroup.class.getSimpleName(); 28 | } 29 | 30 | @Override 31 | public void startup() throws Exception { 32 | defaultEventExecutorGroup = new DefaultEventExecutorGroup(GlobalConstants.NettyNet.NETTY_NET_HTTP_MESSAGE_THREAD_CORE_NUMBER); 33 | } 34 | 35 | @Override 36 | public void shutdown() throws Exception { 37 | if(defaultEventExecutorGroup != null){ 38 | defaultEventExecutorGroup.shutdownGracefully(); 39 | } 40 | } 41 | 42 | public DefaultEventExecutorGroup getDefaultEventExecutorGroup() { 43 | return defaultEventExecutorGroup; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/client/NettyAsyncRPCCallback.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.client; /** * rpc远程回调接口 * @author twjitm - [Created on 2018-08-20 11:46] * @jdk java version "1.8.0_77" * */ public interface NettyAsyncRPCCallback { void success(Object result); void fail(Exception e); } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/client/NettyRpcContextHolder.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.client; /** * rpc信息上下文持有者 * * @author twjitm - [Created on 2018-08-20 12:28] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class NettyRpcContextHolder { /** * 采用ThreadLocal 模式实现一个线程安全的上下文切换。 */ private static final ThreadLocal contextHolder = new ThreadLocal(); public static NettyRpcContextHolderObject getContext() { return (NettyRpcContextHolderObject) contextHolder.get(); } /** * 通过字符串选择数据源 * * @param */ public static void setContextHolder(NettyRpcContextHolderObject rpcContextHolderObject) { contextHolder.set(rpcContextHolderObject); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/client/NettyRpcContextHolderObject.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.client; import com.twjitm.core.common.enums.NettyGameTypeEnum; /** * rpc上下文持有者对像。主要包含请求信息,服务器信息,请求类型 * 在rpc请求之前需要将基本信息保存到此对象中,底层需要获取基本消息,来路由 * 到具体的远程服务器上。 * * @author twjitm - [Created on 2018-08-20 12:31] * @jdk java version "1.8.0_77" */ public class NettyRpcContextHolderObject { private NettyGameTypeEnum nettyGameTypeEnum; private int serviceId; public NettyRpcContextHolderObject(NettyGameTypeEnum nettyGameTypeEnum, int serviceId) { this.nettyGameTypeEnum = nettyGameTypeEnum; this.serviceId = serviceId; } public NettyGameTypeEnum getNettyGameTypeEnum() { return nettyGameTypeEnum; } public void setNettyGameTypeEnum(NettyGameTypeEnum nettyGameTypeEnum) { this.nettyGameTypeEnum = nettyGameTypeEnum; } public int getServiceId() { return serviceId; } public void setServiceId(int serviceId) { this.serviceId = serviceId; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/client/proxy/INettyAsyncRpcProxy.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.client.proxy; import com.twjitm.core.common.service.rpc.client.NettyRpcFuture; /** * @author twjitm - [Created on 2018-08-20 14:45] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public interface INettyAsyncRpcProxy { public NettyRpcFuture call(String funcName, Object... args); } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/manager/NettyDbRpcConnectManager.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.manager; import com.twjitm.core.common.service.rpc.client.AbstractNettyRpcConnectManager; import org.springframework.stereotype.Service; /** * @author twjitm - [Created on 2018-08-20 13:50] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ @Service public class NettyDbRpcConnectManager extends AbstractNettyRpcConnectManager { } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/manager/NettyGameRpcConnectManager.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.manager; import com.twjitm.core.common.service.rpc.client.AbstractNettyRpcConnectManager; import org.springframework.stereotype.Service; /** * @author twjitm - [Created on 2018-08-20 13:51] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ @Service public class NettyGameRpcConnectManager extends AbstractNettyRpcConnectManager { } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/manager/NettyWorldRpcConnectManager.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.manager; import com.twjitm.core.common.service.rpc.client.AbstractNettyRpcConnectManager; import org.springframework.stereotype.Service; /** * @author twjitm - [Created on 2018-08-20 13:51] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ @Service public class NettyWorldRpcConnectManager extends AbstractNettyRpcConnectManager { } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/serialize/INettyJsonSerializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.serialize; import java.io.IOException; /** * @author twjitm - [Created on 2018-08-22 11:01] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public interface INettyJsonSerializer { public String serialize() throws IOException; public void deserialize(String pack); } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/serialize/INettyRpcSerialize.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.serialize; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: 文江 Date: 2018/8/19 Time: 9:21 6 | * https://blog.csdn.net/baidu_23086307 7 | */ 8 | public interface INettyRpcSerialize { 9 | byte[] serialize(T obj); 10 | 11 | T deserialize(byte[] data, Class cls); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/server/NettyRpcNodeInfo.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.server; /** * @author twjitm - [Created on 2018-08-20 11:03] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class NettyRpcNodeInfo { /** * 服务器id */ private String serverId; /** * 服务ip */ private String host; /** * 端口 */ private String port; public String getServerId() { return serverId; } public void setServerId(String serverId) { this.serverId = serverId; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public int getIntPort(){ return Integer.parseInt(port); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/server/NettySdRpcServiceProvider.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.server; import com.twjitm.core.common.enums.NettyGameTypeEnum; import org.jdom2.DataConversionException; import org.jdom2.Element; import java.util.BitSet; /** * @author twjitm - [Created on 2018-08-20 14:20] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class NettySdRpcServiceProvider { private BitSet bitSet = new BitSet(); public void load(Element element) throws DataConversionException { String boenumString = element.getAttribute("boenum").getValue(); NettyGameTypeEnum boEnum = NettyGameTypeEnum.valueOf(boenumString.toUpperCase()); bitSet.set(boEnum.getBoId(), true); } //是否世界开放 public boolean isWorldOpen(){ return bitSet.get(NettyGameTypeEnum.WORLD.getBoId()); } public boolean isGameOpen(){ return bitSet.get(NettyGameTypeEnum.GAME.getBoId()); } public boolean isDbOpen(){ return bitSet.get(NettyGameTypeEnum.DB.getBoId()); } public boolean validServer(int boId){ return bitSet.get(boId); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/service/NettyRemoteRpcHandlerService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.service; 2 | 3 | import com.twjitm.core.common.config.global.NettyGameServiceConfig; 4 | import com.twjitm.core.common.config.global.NettyGameServiceConfigService; 5 | import com.twjitm.core.common.factory.thread.NettyRpcHandlerThreadPoolFactory; 6 | import com.twjitm.core.common.service.IService; 7 | import com.twjitm.core.spring.SpringServiceManager; 8 | import com.twjitm.threads.utils.ExecutorUtil; 9 | import org.springframework.stereotype.Service; 10 | 11 | /** 12 | * Created by IntelliJ IDEA. 13 | * User: 文江 Date: 2018/8/19 Time: 10:29 14 | * https://blog.csdn.net/baidu_23086307 15 | */ 16 | @Service 17 | public class NettyRemoteRpcHandlerService implements IService { 18 | 19 | private NettyRpcHandlerThreadPoolFactory rpcHandlerThreadPool; 20 | 21 | @Override 22 | public String getId() { 23 | return "NettyRemoteRpcHandlerService"; 24 | } 25 | 26 | @Override 27 | public void startup() throws Exception { 28 | NettyGameServiceConfigService config = SpringServiceManager.getSpringLoadService().getNettyGameServiceConfigService(); 29 | NettyGameServiceConfig gameConfig = config.getNettyGameServiceConfig(); 30 | if (gameConfig.isRpcOpen()) { 31 | //开启服务 32 | rpcHandlerThreadPool= SpringServiceManager.getSpringLoadService(). 33 | getNettyRpcHandlerThreadPoolFactory(); 34 | rpcHandlerThreadPool.createExecutor( 35 | gameConfig.getRpcConnectThreadSize(), 36 | gameConfig.getRpcSendProxyThreadSize()); 37 | } 38 | } 39 | 40 | @Override 41 | public void shutdown() throws Exception { 42 | ExecutorUtil.shutdownAndAwaitTermination(SpringServiceManager.getSpringLoadService().getNettyRpcHandlerThreadPoolFactory().getExecutor()); 43 | } 44 | 45 | public void submit(Runnable runnable) { 46 | if(rpcHandlerThreadPool!=null){ 47 | rpcHandlerThreadPool.getExecutor().submit(runnable); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/system/System.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.system; /** * @author twjitm - [Created on 2018-08-17 10:55] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class System { private SystemType type; private String version; public enum SystemType { LINUX(0, "linux"), WINDOWS(1, "windows"), MAC(2, "mac"); private int value; private String name; SystemType(int value, String name) { this.value = value; this.name = name; } } public SystemType getType() { return type; } public void setType(SystemType type) { this.type = type; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/system/SystemService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.system; import com.twjitm.core.utils.logs.LoggerUtils; import org.apache.log4j.Logger; import java.util.Properties; /** * @author twjitm - [Created on 2018-08-17 10:53] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" * system service */ public class SystemService { private static Logger logger = LoggerUtils.getLogger(SystemService.class); public static System getSystem() { Properties properties = java.lang.System.getProperties(); String os = properties.getProperty("os.name"); System system = new System(); System.SystemType type = null; if (os.contains("windows")) { type = System.SystemType.WINDOWS; } if (os.contains("linux") || os.contains("centos") || os.contains("ubuntu")) { type = System.SystemType.LINUX; } if (os.contains("mac")) { type = System.SystemType.MAC; } system.setVersion(os); system.setType(type); logger.info("OPERATING SYSTEM: " + os); logger.info("JAVA RUNTIME VERSION: " + properties.getProperty("java.runtime.version")); logger.info("JAVA CLASS VERSION: " + properties.getProperty("java.class.version")); logger.info("JAVA VM VERSION: " + properties.getProperty("java.vm.version")); return system; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/update/IUpdatable.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.update; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-07-24 19:56] 5 | * @company https://github.com/twjitm/ 6 | * @jdk java version "1.8.0_77" 7 | */ 8 | public interface IUpdatable { 9 | public boolean update(); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/update/UpdateService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.update; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-08-15 11:06] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public class UpdateService { 11 | 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/zookeeper/NettyZookeeperNodeNettyGameTypeEnum.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.zookeeper; import com.twjitm.core.common.enums.NettyGameTypeEnum; /** * @author twjitm - [Created on 2018-08-22 10:42] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" * zookeeper 节点枚举 */ public enum NettyZookeeperNodeNettyGameTypeEnum { WORLD(NettyGameTypeEnum.WORLD, "/registry_world_address"), GAME(NettyGameTypeEnum.GAME, "/registry_game_address"), DB(NettyGameTypeEnum.DB, "/registry_db_address"),; private NettyGameTypeEnum nettyGameTypeEnum; private String rootPath; NettyZookeeperNodeNettyGameTypeEnum(NettyGameTypeEnum nettyGameTypeEnum, String rootPath) { this.nettyGameTypeEnum = nettyGameTypeEnum; this.rootPath = rootPath; } public NettyGameTypeEnum getNettyGameTypeEnum() { return nettyGameTypeEnum; } public void setNettyGameTypeEnum(NettyGameTypeEnum nettyGameTypeEnum) { this.nettyGameTypeEnum = nettyGameTypeEnum; } public String getRootPath() { return rootPath; } public void setRootPath(String rootPath) { this.rootPath = rootPath; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/initalizer/NettyHttpMessageServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.initalizer; 2 | 3 | import com.twjitm.core.common.handler.http.NettyNetMessageHttpServerHandler; 4 | import com.twjitm.core.common.service.http.AsyncNettyHttpHandlerService; 5 | import com.twjitm.core.spring.SpringServiceManager; 6 | import io.netty.channel.Channel; 7 | import io.netty.channel.ChannelInitializer; 8 | import io.netty.channel.ChannelPipeline; 9 | import io.netty.channel.socket.SocketChannel; 10 | import io.netty.handler.codec.http.HttpRequestDecoder; 11 | import io.netty.handler.codec.http.HttpResponseEncoder; 12 | 13 | public class NettyHttpMessageServerInitializer extends ChannelInitializer { 14 | @Override 15 | protected void initChannel(SocketChannel socketChannel) throws Exception { 16 | ChannelPipeline channelPipLine = socketChannel.pipeline(); 17 | //use netty self encoder and decoder 18 | channelPipLine.addLast("encoder", new HttpResponseEncoder()); 19 | channelPipLine.addLast("decoder", new HttpRequestDecoder()); 20 | AsyncNettyHttpHandlerService asyncNettyHttpHandlerService = SpringServiceManager.getSpringLoadService().getAsyncNettyHttpHandlerService(); 21 | channelPipLine.addLast(asyncNettyHttpHandlerService.getDefaultEventExecutorGroup(),new NettyNetMessageHttpServerHandler()); 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/initalizer/NettyRpcClientMessageServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.initalizer; import com.twjitm.core.common.handler.rpc.NettyRpcClientServerHandler; import com.twjitm.core.common.netstack.coder.decode.rpc.NettyNetMessageRPCDecoder; import com.twjitm.core.common.netstack.coder.encode.rpc.NettyNetMessageRPCEncoder; import com.twjitm.core.common.netstack.entity.rpc.NettyRpcRequestMessage; import com.twjitm.core.common.netstack.entity.rpc.NettyRpcResponseMessage; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * @author twjitm - [Created on 2018-08-20 11:27] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" * rpc 客戶端登陸 */ public class NettyRpcClientMessageServerInitializer extends ChannelInitializer { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline channelPipeline = socketChannel.pipeline(); int maxLength = Integer.MAX_VALUE; channelPipeline.addLast(new LengthFieldBasedFrameDecoder(maxLength, 0, 4, 0, 0)); channelPipeline.addLast(new NettyNetMessageRPCEncoder(NettyRpcRequestMessage.class)); channelPipeline.addLast(new NettyNetMessageRPCDecoder(NettyRpcResponseMessage.class)); channelPipeline.addLast("logger", new LoggingHandler(LogLevel.DEBUG)); channelPipeline.addLast(new NettyRpcClientServerHandler()); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/initalizer/NettyRpcMessageServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.initalizer; 2 | 3 | import com.twjitm.core.common.config.global.GlobalConstants; 4 | import com.twjitm.core.common.handler.rpc.NettyNetRPCServerHandler; 5 | import com.twjitm.core.common.netstack.coder.decode.rpc.NettyNetMessageRPCDecoder; 6 | import com.twjitm.core.common.netstack.coder.encode.rpc.NettyNetMessageRPCEncoder; 7 | import com.twjitm.core.common.netstack.entity.rpc.NettyRpcRequestMessage; 8 | import com.twjitm.core.common.netstack.entity.rpc.NettyRpcResponseMessage; 9 | import io.netty.channel.ChannelInitializer; 10 | import io.netty.channel.ChannelPipeline; 11 | import io.netty.channel.socket.nio.NioSocketChannel; 12 | import io.netty.handler.codec.LengthFieldBasedFrameDecoder; 13 | import io.netty.handler.logging.LogLevel; 14 | import io.netty.handler.logging.LoggingHandler; 15 | import io.netty.handler.timeout.IdleStateHandler; 16 | 17 | /** 18 | * Created by IntelliJ IDEA. 19 | * User: 文江 Date: 2018/8/19 Time: 10:19 20 | * https://blog.csdn.net/baidu_23086307 21 | */ 22 | public class NettyRpcMessageServerInitializer extends ChannelInitializer { 23 | 24 | @Override 25 | protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception { 26 | ChannelPipeline pipeline = nioSocketChannel.pipeline(); 27 | int maxLength = Integer.MAX_VALUE; 28 | pipeline.addLast("frame", new LengthFieldBasedFrameDecoder(maxLength, 0, 4, 0, 0)); 29 | pipeline.addLast("decoder", new NettyNetMessageRPCDecoder(NettyRpcRequestMessage.class)); 30 | pipeline.addLast("encoder", new NettyNetMessageRPCEncoder(NettyRpcResponseMessage.class)); 31 | int readerIdleTimeSeconds = 0; 32 | int writerIdleTimeSeconds = 0; 33 | int allIdleTimeSeconds = GlobalConstants.NettyNet.SESSION_HEART_ALL_TIMEOUT; 34 | pipeline.addLast("idleStateHandler", new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds)); 35 | pipeline.addLast("logger", new LoggingHandler(LogLevel.DEBUG)); 36 | pipeline.addLast("handler", new NettyNetRPCServerHandler()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/initalizer/NettyTcpMessageServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.initalizer; 2 | 3 | import com.twjitm.core.common.config.global.GlobalConstants; 4 | import com.twjitm.core.common.handler.tcp.NettyNetLoggingHandler; 5 | import com.twjitm.core.common.handler.tcp.NettyNetMessageTcpServerHandler; 6 | import com.twjitm.core.common.netstack.coder.decode.tcp.NettyNetProtoBufMessageTCPDecoder; 7 | import com.twjitm.core.common.netstack.coder.encode.tcp.NettyNetProtoBufMessageTCPEncoder; 8 | import com.twjitm.core.test.TestServiceHandler; 9 | import io.netty.channel.Channel; 10 | import io.netty.channel.ChannelInitializer; 11 | import io.netty.handler.codec.LengthFieldBasedFrameDecoder; 12 | import io.netty.handler.logging.LogLevel; 13 | import io.netty.handler.timeout.IdleStateHandler; 14 | 15 | /** 16 | * Created by 文江 on 2017/11/25. 17 | * TCP协议初始化器 18 | */ 19 | public class NettyTcpMessageServerInitializer extends ChannelInitializer { 20 | @Override 21 | protected void initChannel(Channel ch) throws Exception { 22 | ch.pipeline().addLast("frame", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 2, 4, 0, 0)); 23 | ch.pipeline().addLast(new NettyNetProtoBufMessageTCPDecoder()); 24 | ch.pipeline().addLast(new NettyNetProtoBufMessageTCPEncoder()); 25 | //添加心跳檢測 26 | int readerIdleTimeSeconds = GlobalConstants.NettyNet.SESSION_HEART_READ_TIMEOUT; 27 | int writerIdleTimeSeconds = GlobalConstants.NettyNet.SESSION_HEART_WRITE_TIMEOUT; 28 | int allIdleTimeSeconds = GlobalConstants.NettyNet.SESSION_HEART_ALL_TIMEOUT; 29 | ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds)); 30 | 31 | //ch.pipeline().addLast(new TestServiceHandler()); 32 | ch.pipeline().addLast(new NettyNetLoggingHandler(LogLevel.DEBUG)); 33 | ch.pipeline().addLast(new NettyNetMessageTcpServerHandler()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/initalizer/NettyUdpMessageServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.initalizer; 2 | 3 | import com.twjitm.core.common.handler.udp.NettyNetMessageUdpServerHandler; 4 | import com.twjitm.core.common.netstack.coder.decode.udp.NettyNetProtoBufMessageUDPDecoder; 5 | import com.twjitm.core.common.netstack.coder.encode.udp.NettyNetProtoBufMessageUDPEncoder; 6 | import io.netty.channel.ChannelInitializer; 7 | import io.netty.channel.ChannelPipeline; 8 | import io.netty.channel.socket.nio.NioDatagramChannel; 9 | import io.netty.handler.codec.LengthFieldBasedFrameDecoder; 10 | import io.netty.handler.logging.LogLevel; 11 | import io.netty.handler.logging.LoggingHandler; 12 | 13 | /** 14 | * udp协议初始化器 15 | */ 16 | public class NettyUdpMessageServerInitializer extends ChannelInitializer { 17 | @Override 18 | protected void initChannel(NioDatagramChannel ch) throws Exception { 19 | ChannelPipeline channelPipLine = ch.pipeline(); 20 | int maxLength = Integer.MAX_VALUE; 21 | ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(maxLength, 2, 4, 0, 0)); 22 | ch.pipeline().addLast(new NettyNetProtoBufMessageUDPEncoder()); 23 | ch.pipeline().addLast(new NettyNetProtoBufMessageUDPDecoder()); 24 | channelPipLine.addLast("logger", new LoggingHandler(LogLevel.DEBUG)); 25 | channelPipLine.addLast(new NettyNetMessageUdpServerHandler()); 26 | 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/initalizer/NettyWebSocketServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.initalizer; 2 | 3 | 4 | import com.twjitm.core.common.handler.http.HttpRequestHandler; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.ChannelPipeline; 7 | import io.netty.channel.socket.SocketChannel; 8 | import io.netty.handler.codec.http.HttpObjectAggregator; 9 | import io.netty.handler.codec.http.HttpServerCodec; 10 | import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; 11 | import io.netty.handler.stream.ChunkedWriteHandler; 12 | 13 | /** 14 | * Created by 文江 on 2017/9/25. 15 | */ 16 | public class NettyWebSocketServerInitializer extends ChannelInitializer { 17 | @Override 18 | public void initChannel(SocketChannel ch) throws Exception {//2 19 | ChannelPipeline pipeline = ch.pipeline(); 20 | 21 | pipeline.addLast(new HttpServerCodec()); 22 | pipeline.addLast(new HttpObjectAggregator(64 * 1024)); 23 | pipeline.addLast(new ChunkedWriteHandler()); 24 | 25 | pipeline.addLast(new HttpRequestHandler("/ws")); 26 | pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); 27 | 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/player/dao/PlayerDao.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.player.dao; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-08-08 20:16] 5 | * @company https://github.com/twjitm/ 6 | * @jdk java version "1.8.0_77" 7 | */ 8 | public class PlayerDao { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/player/entity/GameNettyPlayer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.player.entity; 2 | 3 | import com.twjitm.core.common.netstack.sender.NettyNetTcpMessageSender; 4 | import com.twjitm.core.common.service.ILongId; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-08-08 13:52] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | */ 11 | public class GameNettyPlayer implements IGameNettyPlayer, ILongId { 12 | 13 | //玩家id 14 | private long playerId; 15 | //玩家的udp token 16 | private int udpToken; 17 | 18 | private NettyNetTcpMessageSender netTcpMessageSender; 19 | 20 | public GameNettyPlayer(long playerId, int udpToken, NettyNetTcpMessageSender netTcpMessageSender) { 21 | this.playerId = playerId; 22 | this.udpToken = udpToken; 23 | this.netTcpMessageSender = netTcpMessageSender; 24 | } 25 | 26 | @Override 27 | public long getLongId() { 28 | return this.playerId; 29 | } 30 | 31 | @Override 32 | public long getPlayerId() { 33 | return this.playerId; 34 | } 35 | 36 | @Override 37 | public int getPlayerUdpToken() { 38 | return this.udpToken; 39 | } 40 | 41 | @Override 42 | public NettyNetTcpMessageSender getNetTcpMessageSender() { 43 | return this.netTcpMessageSender; 44 | } 45 | 46 | public void setNetTcpMessageSender(NettyNetTcpMessageSender netTcpMessageSender) { 47 | this.netTcpMessageSender = netTcpMessageSender; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/player/entity/IGameNettyPlayer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.player.entity; 2 | 3 | import com.twjitm.core.common.netstack.sender.NettyNetTcpMessageSender; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-08-08 13:55] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public interface IGameNettyPlayer { 11 | public long getPlayerId(); 12 | public int getPlayerUdpToken(); 13 | public NettyNetTcpMessageSender getNetTcpMessageSender(); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/service/dispatcher/IDispatcherService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.service.dispatcher; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 5 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 6 | import com.twjitm.core.common.netstack.entity.rpc.NettyRpcRequestMessage; 7 | 8 | /** 9 | * Created by twjitm on 2018/4/27. 10 | */ 11 | public interface IDispatcherService { 12 | /** 13 | * 网络消息分发器 14 | * @param message 15 | * @return 16 | */ 17 | public AbstractNettyNetProtoBufMessage dispatcher(AbstractNettyNetMessage message); 18 | 19 | /** 20 | * rpc消息分发器 21 | * @param request 22 | * @return 23 | * @throws Throwable 24 | */ 25 | public Object dispatcher(NettyRpcRequestMessage request) throws Throwable; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/service/rpc/infor.java: -------------------------------------------------------------------------------- 1 | /** * 暴露的远程服务,远程服务RPC,为以其他服务器通过自定义规则来实现远程调用 * 每一个服务类接口必须注解为NettyRpcServiceAnnotation 类型 * 标记为这个类中所有的方法都是用来提供远程RPC调用的。 * NettyRpcServiceAnnotation 必须要标记在实现类上,调用的时候而需要传入 * 实现类的接口名称,否者将发生反射异常。 */ -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/service/rpc/service/HelloWorldImpl.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.service.rpc.service; import com.twjitm.core.common.annotation.NettyRpcServiceAnnotation; import com.twjitm.core.utils.logs.LoggerUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Repository; /** * @author twjitm - [Created on 2018-08-20 10:26] * @jdk java version "1.8.0_77" * 这个地方一定是注入的是业务对象的接口~~~~~~~~~~~~~~~~ */ @NettyRpcServiceAnnotation(IHelloWorld.class) @Repository public class HelloWorldImpl implements IHelloWorld { private Logger logger = LoggerUtils.getLogger(HelloWorldImpl.class); @Override public String getHelloWorld(int number) { StringBuilder builder = new StringBuilder(); for (int i = number; i > 0; i--) { builder.append("helloworld"); builder.append(i); } System.out.println("rpc 远程调用方法成功。。。。。,即将返回给远程客户端调用"); return builder.toString(); } class Task implements Runnable{ @Override public void run() { } } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/service/rpc/service/IHelloWorld.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.service.rpc.service; /** * @author twjitm - [Created on 2018-08-20 10:24] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public interface IHelloWorld { String getHelloWorld(int number); } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/service/user/Impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.service.user.Impl; 2 | 3 | import com.twjitm.core.service.user.UserService; 4 | import org.springframework.stereotype.Service; 5 | 6 | /** 7 | * Created by 文江 on 2018/4/16. 8 | */ 9 | @Service 10 | public class UserServiceImpl implements UserService { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/service/user/UserService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.service.user; 2 | 3 | /** 4 | * Created by 文江 on 2018/4/16. 5 | */ 6 | public interface UserService { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/test/AsyncExecutorService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.test; import com.twjitm.core.player.entity.GameNettyPlayer; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; /** * spring 异步任务 * * @author twjitm - [Created on 2018-08-31 16:45] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ @Service public class AsyncExecutorService { @Async public void saveUser(GameNettyPlayer player){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("async insert db"); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/test/TestJson.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.test; 2 | 3 | import com.alibaba.fastjson.JSONArray; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** 9 | * @author by twjitm on 2018/11/9/11:35 10 | */ 11 | public class TestJson { 12 | 13 | public static void main(String[] args) { 14 | test(); 15 | } 16 | 17 | private static void test() { 18 | List testlist = new ArrayList<>(); 19 | for (int i = 0; i < 2; i++) { 20 | Text text = new Text(); 21 | text.setContext("hhshah" + i); 22 | text.setIsdefault(true); 23 | text.setLanguage("en"); 24 | testlist.add(text); 25 | } 26 | System.out.println(JSONArray.toJSONString(testlist)); 27 | 28 | 29 | } 30 | 31 | 32 | public static class Text { 33 | private String language; 34 | private String context; 35 | private boolean isdefault; 36 | 37 | public String getLanguage() { 38 | return language; 39 | } 40 | 41 | public void setLanguage(String language) { 42 | this.language = language; 43 | } 44 | 45 | public String getContext() { 46 | return context; 47 | } 48 | 49 | public void setContext(String context) { 50 | this.context = context; 51 | } 52 | 53 | public boolean isIsdefault() { 54 | return isdefault; 55 | } 56 | 57 | public void setIsdefault(boolean isdefault) { 58 | this.isdefault = isdefault; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/test/TestServiceHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.test; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 4 | import com.twjitm.core.spring.SpringLoadServiceImpl; 5 | import com.twjitm.core.spring.SpringServiceManager; 6 | import com.twjitm.core.utils.logs.LoggerUtils; 7 | import io.netty.channel.Channel; 8 | import io.netty.channel.ChannelHandlerContext; 9 | import io.netty.channel.ChannelInboundHandlerAdapter; 10 | import org.apache.log4j.Logger; 11 | 12 | import java.util.ArrayList; 13 | import java.util.HashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | 17 | /** 18 | * Created by 文江 on 2018/5/16. 19 | */ 20 | public class TestServiceHandler extends ChannelInboundHandlerAdapter { 21 | Logger logger = LoggerUtils.getLogger(TestServiceHandler.class); 22 | private Map map = new HashMap(); 23 | private List list = new ArrayList(); 24 | private SpringLoadServiceImpl springLoadManager = SpringServiceManager.springLoadService; 25 | 26 | @Override 27 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 28 | super.channelActive(ctx); 29 | logger.info("有新客户端请求建立"); 30 | /* ctx.writeAndFlush("你好,客户端");*/ 31 | } 32 | 33 | @Override 34 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 35 | super.channelRead(ctx, msg); 36 | map.put(ctx.channel().id().asLongText(), ctx.channel()); 37 | System.out.println("hahahahah"); 38 | System.out.println(ctx.channel().remoteAddress() + "->Server :" + msg.toString()); 39 | System.out.println(ctx.channel().id()); 40 | AbstractNettyNetProtoBufMessage message = springLoadManager.getDispatcherService().dispatcher((AbstractNettyNetProtoBufMessage) msg); 41 | /* ctx.channel().writeAndFlush("服务器对大家说的话!"); 42 | for (Channel channel : list) { 43 | channel.writeAndFlush("广播的消息"); 44 | }*/ 45 | /*list.add(ctx.channel()); 46 | ctx.flush();*/ 47 | ctx.writeAndFlush(message); 48 | } 49 | 50 | public void test() { 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/test/TestWorldChatService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.test; import com.twjitm.core.common.service.IService; import com.twjitm.core.spring.SpringServiceManager; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author twjitm - [Created on 2018-09-20 16:55] */ public class TestWorldChatService implements IService { @Override public String getId() { return null; } @Override public void startup() throws Exception { ExecutorService executorService=Executors.newCachedThreadPool(); executorService.execute(new WorldChatTask()); } @Override public void shutdown() throws Exception { } class WorldChatTask implements Runnable{ @Override public void run() { while (true){ SpringServiceManager.getSpringLoadService().getNettyKafkaProducerListener(); } } } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/utils/logs/LoggerUtils.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.utils.logs; 2 | 3 | import org.apache.log4j.Logger; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-07-18 17:14] 7 | * @jdk java version "1.8.0_77" 8 | */ 9 | public class LoggerUtils { 10 | 11 | public static Logger getLogger(Class clzz) { 12 | return Logger.getLogger(clzz); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/utils/spring/BeanUtils.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.utils.spring; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * @author twjitm - [Created on 2018-07-27 11:03] 10 | * @company https://github.com/twjitm/ 11 | * @jdk java version "1.8.0_77" 12 | */ 13 | @Service 14 | public class BeanUtils implements ApplicationContextAware { 15 | private static ApplicationContext ctx; 16 | @Override 17 | public void setApplicationContext(ApplicationContext arg0)throws BeansException { 18 | ctx = arg0; 19 | } 20 | 21 | public static Object getBean(String beanName) { 22 | if(ctx == null){ 23 | throw new NullPointerException(); 24 | } 25 | return ctx.getBean(beanName); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/utils/time/timer/ExpirationListener.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.utils.time.timer; /** * @author twjitm - [Created on 2018-08-31 10:36] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public interface ExpirationListener { /** * 过期的任务清理 * * @param expireObject */ void expired(E expireObject); } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/utils/time/timer/TimeSlot.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.utils.time.timer; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; /** * 时间槽 * * @author twjitm - [Created on 2018-08-31 10:34] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class TimeSlot { /** * 时间槽id */ private int id; /** * 槽元素 */ private Set elements = new ConcurrentSkipListSet(); public TimeSlot(int id) { this.id = id; } public void add(E e) { elements.add(e); } public boolean remove(E e) { return elements.remove(e); } public Set getElements() { return elements; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TimeSlot timeSlot = (TimeSlot) obj; if (timeSlot.id != id) { return false; } return true; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/utils/uuid/AtomicLimitNumber.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.utils.uuid; 2 | 3 | import java.util.concurrent.atomic.AtomicLong; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-07-26 20:46] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public class AtomicLimitNumber { 11 | /** 12 | * 原子数量 13 | */ 14 | private AtomicLong atomicLong; 15 | 16 | public AtomicLimitNumber() { 17 | this.atomicLong = new AtomicLong(); 18 | } 19 | 20 | public long increment(){ 21 | return this.atomicLong.incrementAndGet(); 22 | } 23 | 24 | public long decrement(){ 25 | return this.atomicLong.decrementAndGet(); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/utils/uuid/LongIdGenerator.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.utils.uuid; 2 | 3 | 4 | import java.util.concurrent.atomic.AtomicLong; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-07-24 19:41] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | */ 11 | public class LongIdGenerator { 12 | protected AtomicLong id_gen = new AtomicLong(0); 13 | 14 | public long generateId(){ 15 | return id_gen.incrementAndGet(); 16 | } 17 | 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/zookeeper/Constant.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.zookeeper; 2 | 3 | /** 4 | * Created by on 2018/4/17. 5 | * ZOOKEEPER 6 | */ 7 | public class Constant { 8 | public static final int ZK_SESSION_TIMEOUT = 20000; 9 | public static String ZK_REGISTRY_PATH; 10 | public static String ZK_DATA_PATH; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/resources/bean/game-kafka.properties: -------------------------------------------------------------------------------- 1 | kafka.taskThreadSize=4 kafka.corePoolSize=4 kafka.maximumPoolSize=4 kafka.keepAliveTime=5000 -------------------------------------------------------------------------------- /src/main/resources/bean/game-properties.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twjitm/twjitm-core/85f60459c36028b48f1c3b47ee09d67c2befffb1/src/main/resources/bean/game-properties.properties -------------------------------------------------------------------------------- /src/main/resources/bean/game-zookeeper.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twjitm/twjitm-core/85f60459c36028b48f1c3b47ee09d67c2befffb1/src/main/resources/bean/game-zookeeper.properties -------------------------------------------------------------------------------- /src/main/resources/bean/log4j2-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | front.log 14 | d:/usr/front/log/ 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 29 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /src/main/resources/bean/netty-http-config.xml: -------------------------------------------------------------------------------- 1 | http_server 21001 127.0.0.1 11030 false 300 -------------------------------------------------------------------------------- /src/main/resources/bean/netty-rpc-config.xml: -------------------------------------------------------------------------------- 1 | rpc_server 11001 127.0.0.1 11040 -------------------------------------------------------------------------------- /src/main/resources/bean/netty-udp-config.xml: -------------------------------------------------------------------------------- 1 | udp_server 11001 127.0.0.1 11020 1 true -------------------------------------------------------------------------------- /src/main/resources/bean/netty-websocket-config.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/bean/rpc-server-register.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/main/resources/bean/rpc-service-register.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twjitm/twjitm-core/85f60459c36028b48f1c3b47ee09d67c2befffb1/src/main/resources/log4j.properties -------------------------------------------------------------------------------- /src/main/resources/mail/mail.properties: -------------------------------------------------------------------------------- 1 | myEmailAccount=1029718215@qq.com myEmailPassword =twjtim456 mail.transport.protocol=smtp mail.smtp.host=smtp.qq.com mail.smtp.auth=true mail.smtp.starttls.enable=true authCode=yfjcfdumqdaebeee -------------------------------------------------------------------------------- /src/main/resources/proto/LoginOnlineClientTcpMessagebuf.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | message LoginOnlineClientTcpMessage { 3 | int64 player_id = 1; 4 | } -------------------------------------------------------------------------------- /src/main/resources/proto/OnlineClientUdpMessageBuf.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | message OnlineClientUdpMessage { 3 | int64 id = 1; 4 | 5 | 6 | } -------------------------------------------------------------------------------- /src/main/resources/proto/OnlineHeratClientHttpMessageBuf.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | option java_multiple_files = true; 3 | 4 | option java_package = "com.twjitm.core.common.proto"; 5 | 6 | message OnlineClientHttpMessage { 7 | int64 player_id = 1; 8 | string player_name = 2; 9 | 10 | } 11 | 12 | message LoginProxy { 13 | string name = 1; 14 | string password = 2; 15 | } -------------------------------------------------------------------------------- /src/main/resources/proto/build.sh: -------------------------------------------------------------------------------- 1 | # 打包proto脚本,在proto.exe 同级目录下执行 2 | .\protoc.exe --java_out=./ your.proto 3 | .\protoc.exe --csharp_out=./ your.proto 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/main/resources/spring/applicationContext-async-task.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/spring/applicationContext-kafka-producer.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/spring/applicationContext-kafka.consumer.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/spring/applicationContext-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/ClientServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.twjitm; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelOption; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioSocketChannel; 9 | 10 | /** 11 | * Created by twjitm on 2018/5/14. 12 | * netty客户端 13 | */ 14 | public class ClientServiceTest { 15 | static String ip = "127.0.0.1"; 16 | static int port = 11010; 17 | 18 | public static void main(String[] args) { 19 | TestSpring.initSpring(); 20 | startup(ip,port); 21 | } 22 | 23 | 24 | public static void startup(String ip, int port) { 25 | EventLoopGroup eventExecutors = new NioEventLoopGroup(); 26 | Bootstrap bootstrap = new Bootstrap(); 27 | // bootstrap.bind(ip,port); 28 | bootstrap.group(eventExecutors); 29 | bootstrap.channel(NioSocketChannel.class); 30 | bootstrap.option(ChannelOption.TCP_NODELAY, true); 31 | bootstrap.handler(new TestChannelInitializer()); 32 | try { 33 | ChannelFuture future = bootstrap.connect(ip, port).sync(); 34 | future.channel().closeFuture().sync(); 35 | 36 | } catch (InterruptedException e) { 37 | e.printStackTrace(); 38 | } 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/TestChannelInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm; 2 | 3 | import com.twjitm.core.common.netstack.coder.decode.tcp.NettyNetProtoBufMessageTCPDecoder; 4 | import com.twjitm.core.common.netstack.coder.encode.tcp.NettyNetProtoBufMessageTCPEncoder; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.handler.codec.LengthFieldBasedFrameDecoder; 8 | 9 | 10 | /** 11 | * Created by 文江 on 2017/11/13. 12 | */ 13 | public class TestChannelInitializer extends ChannelInitializer { 14 | 15 | protected void initChannel(SocketChannel ch) throws Exception { 16 | 17 | int maxLength = Integer.MAX_VALUE; 18 | ch.pipeline().addLast("frame", new LengthFieldBasedFrameDecoder(maxLength, 2, 4, 0, 0)); 19 | ch.pipeline().addLast(new NettyNetProtoBufMessageTCPEncoder()); 20 | ch.pipeline().addLast(new NettyNetProtoBufMessageTCPDecoder()); 21 | ch.pipeline().addLast(new TestClientHandler()); 22 | } 23 | 24 | 25 | /** 26 | * google proto buffer encode and decode; 27 | */ 28 | 29 | /* @Override 30 | protected void initChannel(SocketChannel ch) { 31 | ChannelPipeline pipeline = ch.pipeline(); 32 | 33 | // ----Protobuf处理器,这里的配置是关键---- 34 | pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());// 用于decode前解决半包和粘包问题(利用包头中的包含数组长度来识别半包粘包) 35 | //配置Protobuf解码处理器,消息接收到了就会自动解码,ProtobufDecoder是netty自带的,Message是自己定义的Protobuf类 36 | pipeline.addLast("protobufDecoder", 37 | new ProtobufDecoder(); 38 | // 用于在序列化的字节数组前加上一个简单的包头,只包含序列化的字节长度。 39 | pipeline.addLast("frameEncoder", 40 | new ProtobufVarint32LengthFieldPrepender()); 41 | //配置Protobuf编码器,发送的消息会先经过编码 42 | pipeline.addLast("protobufEncoder", new ProtobufEncoder()); 43 | 44 | }*/ 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/TestClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm; 2 | 3 | import com.twjitm.core.common.entity.online.LoginOnlineClientTcpMessage; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.ChannelInboundHandlerAdapter; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | /** 10 | * Created by 文江 on 2017/11/13. 11 | */ 12 | public class TestClientHandler extends ChannelInboundHandlerAdapter { 13 | private Logger logger=LoggerFactory.getLogger(TestClientHandler.class); 14 | 15 | public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 16 | 17 | 18 | } 19 | 20 | public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { 21 | 22 | } 23 | 24 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 25 | System.out.println("-----------error--------------"+cause.getMessage()); 26 | ctx.close(); 27 | } 28 | 29 | @Override 30 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 31 | /* System.out.println("into channelActive"); 32 | ChatMessage chatMessage=new ChatMessage(); 33 | chatMessage.setChatType(1); 34 | chatMessage.setContext("twjitm"); 35 | chatMessage.setReceiveHaldUrl("url"); 36 | chatMessage.setRead(true); 37 | chatMessage.setReceiveNickName("haha"); 38 | chatMessage.setReceiveSession("gaga"); 39 | chatMessage.setReceiveUId(11); 40 | ctx.writeAndFlush(chatMessage);*/ 41 | for(int i=0;i<100;i++){ 42 | LoginOnlineClientTcpMessage login=new LoginOnlineClientTcpMessage(); 43 | login.setPlayerId(Long.valueOf(10086)); 44 | ctx.writeAndFlush(login); 45 | logger.info("send message to server................................"); 46 | } 47 | 48 | } 49 | 50 | @Override 51 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 52 | super.channelRead(ctx, msg); 53 | System.out.println(msg.toString()); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/TestSpring.java: -------------------------------------------------------------------------------- 1 | package com.twjitm; 2 | 3 | 4 | import com.twjitm.core.spring.SpringServiceManager; 5 | 6 | public class TestSpring { 7 | public static void initSpring(){ 8 | SpringServiceManager.init(); 9 | SpringServiceManager.start(); 10 | } 11 | 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/books/client/EchoClient.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.books.client; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.SocketChannel; 9 | import io.netty.channel.socket.nio.NioSocketChannel; 10 | 11 | import java.net.InetSocketAddress; 12 | 13 | /** 14 | * 客户端引导 15 | */ 16 | public class EchoClient { 17 | public static void main(String[] args) { 18 | start(8081); 19 | } 20 | 21 | private static void start(int port){ 22 | EventLoopGroup group = new NioEventLoopGroup(); 23 | Bootstrap bootstrap = new Bootstrap(); 24 | 25 | bootstrap.group(group).channel(NioSocketChannel.class) 26 | .remoteAddress(new InetSocketAddress("", port)) 27 | .handler(new ChannelInitializer() { 28 | @Override 29 | protected void initChannel(SocketChannel ch) throws Exception { 30 | ch.pipeline().addLast(new EchoClientHandler()); 31 | } 32 | }); 33 | ChannelFuture future = null; 34 | try { 35 | future = bootstrap.connect().sync(); 36 | } catch (InterruptedException e) { 37 | e.printStackTrace(); 38 | } 39 | try { 40 | future.channel().closeFuture().sync(); 41 | } catch (InterruptedException e) { 42 | e.printStackTrace(); 43 | } 44 | finally { 45 | try { 46 | group.shutdownGracefully().await(); 47 | } catch (InterruptedException e) { 48 | e.printStackTrace(); 49 | } 50 | } 51 | 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/books/client/EchoClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.books.client; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerContext; 6 | import io.netty.channel.SimpleChannelInboundHandler; 7 | import io.netty.util.CharsetUtil; 8 | 9 | /** 10 | * Created by on 2018/5/18. 11 | */ 12 | public class EchoClientHandler extends SimpleChannelInboundHandler { 13 | 14 | @Override 15 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 16 | super.channelActive(ctx); 17 | ctx.writeAndFlush(Unpooled.copiedBuffer("netty rocks", CharsetUtil.UTF_8)); 18 | } 19 | 20 | @Override 21 | protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { 22 | System.out.println("client hdfhdfdfh received"+msg.toString(CharsetUtil.UTF_8)); 23 | } 24 | 25 | @Override 26 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 27 | super.exceptionCaught(ctx, cause); 28 | cause.printStackTrace(); 29 | ctx.close(); 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/books/server/EchoServer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.books.server; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelOption; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioServerSocketChannel; 9 | 10 | /** 11 | * Created by 文江 on 2018/5/18. 12 | */ 13 | public class EchoServer { 14 | private static int port; 15 | 16 | public EchoServer(int port) { 17 | this.port = port; 18 | } 19 | 20 | public static void main(String[] args) { 21 | new EchoServer(8081).start(); 22 | } 23 | 24 | public static void start() { 25 | final EchoServiceHandler echoServiceHandler = new EchoServiceHandler(); 26 | EventLoopGroup group = new NioEventLoopGroup(); 27 | EventLoopGroup listenIntoGroup = new NioEventLoopGroup(); // (1) 28 | EventLoopGroup progressGroup = new NioEventLoopGroup(); 29 | ServerBootstrap b = new ServerBootstrap(); // (2) 30 | b.group(listenIntoGroup, progressGroup) 31 | .channel(NioServerSocketChannel.class) // (3) 32 | .childHandler(echoServiceHandler) //(4) 33 | .option(ChannelOption.SO_BACKLOG, 128) // (5) 34 | .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)*/ 35 | // 绑定端口,开始接收进来的连接 36 | ChannelFuture f = null; // (7) 37 | try { 38 | f = b.bind("127.0.0.1", port).sync(); 39 | System.out.println("服务器启动了"); 40 | f.channel().closeFuture().sync(); 41 | } catch (InterruptedException e) { 42 | e.printStackTrace(); 43 | } finally { 44 | listenIntoGroup.shutdownGracefully(); 45 | progressGroup.shutdownGracefully(); 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/books/server/EchoServiceHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.books.server; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelFutureListener; 6 | import io.netty.channel.ChannelHandler; 7 | import io.netty.channel.ChannelHandlerContext; 8 | import io.netty.channel.ChannelInboundHandlerAdapter; 9 | import io.netty.util.CharsetUtil; 10 | 11 | /** 12 | * Created by 文江 on 2018/5/17. 13 | */ 14 | @ChannelHandler.Sharable 15 | public class EchoServiceHandler extends ChannelInboundHandlerAdapter { 16 | @Override 17 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 18 | ByteBuf byteBuf = (ByteBuf) msg; 19 | System.out.println(byteBuf.toString(CharsetUtil.UTF_8)); 20 | ctx.write(byteBuf); 21 | } 22 | 23 | @Override 24 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 25 | ctx.writeAndFlush(Unpooled.BIG_ENDIAN).addListener(ChannelFutureListener.CLOSE); 26 | } 27 | 28 | @Override 29 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 30 | cause.printStackTrace(); 31 | ctx.close(); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/email/MailMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.email; import java.util.Date; /** * @author twjitm - [Created on 2018-08-24 12:17] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class MailMessage { private String context; private Date date; public String getContext() { return context; } public void setContext(String context) { this.context = context; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/email/User.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.email; import java.util.Date; /** * @author twjitm - [Created on 2018-08-24 12:21] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class User { private long id; private String email; private String password; private String username; private String role; private int status; private Date regTime; private String regIp; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getRegTime() { return regTime; } public void setRegTime(Date regTime) { this.regTime = regTime; } public String getRegIp() { return regIp; } public void setRegIp(String regIp) { this.regIp = regIp; } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/http/GameHttpClientInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.http; 2 | 3 | import io.netty.channel.ChannelInitializer; 4 | import io.netty.channel.ChannelPipeline; 5 | import io.netty.channel.socket.SocketChannel; 6 | import io.netty.handler.codec.http.HttpRequestEncoder; 7 | import io.netty.handler.codec.http.HttpResponseDecoder; 8 | import io.netty.handler.ssl.SslContext; 9 | 10 | /** 11 | * Created by twjitm on 2017/9/29. 12 | */ 13 | public class GameHttpClientInitializer extends ChannelInitializer { 14 | 15 | private final SslContext sslCtx; 16 | 17 | public GameHttpClientInitializer(SslContext sslCtx) { 18 | this.sslCtx = sslCtx; 19 | } 20 | 21 | @Override 22 | public void initChannel(SocketChannel ch) { 23 | ChannelPipeline p = ch.pipeline(); 24 | if (sslCtx != null) { 25 | p.addLast(sslCtx.newHandler(ch.alloc())); 26 | } 27 | p.addLast("encoder", new HttpRequestEncoder()); 28 | // p.addLast("trunk", new HttpObjectAggregator(1048576)); 29 | p.addLast("decoder", new HttpResponseDecoder()); 30 | 31 | p.addLast(new GameHttpClientHandler()); 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/kafka/TestKafka.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.kafka; import com.twjitm.TestSpring; import com.twjitm.core.common.kafka.KafkaTaskType; import com.twjitm.core.common.kafka.NettyKafkaProducerListener; import com.twjitm.core.spring.SpringServiceManager; import javax.annotation.Resource; /** * @author twjitm - [Created on 2018-09-05 12:25] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class TestKafka { public static void main(String[] args) { TestSpring.initSpring(); test(); } public static void test() { WordChatTask task = new WordChatTask(KafkaTaskType.WORLD_CHAT); task.setValue("世界,你好"); NettyKafkaProducerListener nettyKafkaProducerListener = SpringServiceManager.getSpringLoadService().getNettyKafkaProducerListener(); nettyKafkaProducerListener.put(task); } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/kafka/WordChatTask.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.kafka; import com.twjitm.core.common.kafka.AbstractKafkaPushTask; import com.twjitm.core.common.kafka.KafkaTaskType; /** * @author twjitm - [Created on 2018-09-05 11:52] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class WordChatTask extends AbstractKafkaPushTask { public WordChatTask(KafkaTaskType taskType) { super(taskType); } @Override public void setValue(Object value) { this.value=value; } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/rpc/HelloWorldCallbackTest.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.rpc; import com.twjitm.TestSpring; import com.twjitm.core.common.enums.NettyGameTypeEnum; import com.twjitm.core.common.service.rpc.client.NettyAsyncRPCCallback; import com.twjitm.core.common.service.rpc.client.NettyRpcFuture; import com.twjitm.core.common.service.rpc.client.NettyRpcContextHolder; import com.twjitm.core.common.service.rpc.client.NettyRpcContextHolderObject; import com.twjitm.core.common.service.rpc.client.proxy.INettyAsyncRpcProxy; import com.twjitm.core.common.service.rpc.service.NettyRpcProxyService; import com.twjitm.core.service.rpc.service.IHelloWorld; import com.twjitm.core.spring.SpringServiceManager; /** * @author twjitm - [Created on 2018-08-20 17:26] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" * 异步回调 */ public class HelloWorldCallbackTest { private static NettyRpcProxyService nettyRpcProxyService; public static void main(String[] args) { init(); } private static void init() { TestSpring.initSpring(); nettyRpcProxyService = SpringServiceManager.getSpringLoadService().getNettyRpcProxyService(); INettyAsyncRpcProxy async = nettyRpcProxyService.createAsync(IHelloWorld.class); NettyRpcContextHolderObject rpcContextHolderObject = new NettyRpcContextHolderObject(NettyGameTypeEnum.WORLD, 9001); NettyRpcContextHolder.setContextHolder(rpcContextHolderObject); NettyRpcFuture rpcFuture = async.call("getHelloWorld", 5); rpcFuture.addCallback(new NettyAsyncRPCCallback() { @Override public void success(Object result) { System.out.println(result); } @Override public void fail(Exception e) { System.out.println(e); } }); } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/rpc/HelloWorldServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.rpc; import com.twjitm.TestSpring; import com.twjitm.core.common.enums.NettyGameTypeEnum; import com.twjitm.core.common.service.rpc.client.NettyRpcContextHolder; import com.twjitm.core.common.service.rpc.client.NettyRpcContextHolderObject; import com.twjitm.core.common.service.rpc.service.NettyRpcProxyService; import com.twjitm.core.service.rpc.service.IHelloWorld; import com.twjitm.core.spring.SpringServiceManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author twjitm - [Created on 2018-08-20 15:16] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" * * 同步阻塞调用 */ public class HelloWorldServiceTest { Logger logger=LoggerFactory.getLogger(HelloWorldServiceTest.class); private NettyRpcProxyService nettyRpcProxyService; public static void main(String[] args) { TestSpring.initSpring(); HelloWorldServiceTest helloServiceTest = new HelloWorldServiceTest(); helloServiceTest.init(); helloServiceTest.helloTest1(); helloServiceTest.setTear(); } private void init() { nettyRpcProxyService=SpringServiceManager.getSpringLoadService().getNettyRpcProxyService(); } private void helloTest1() { IHelloWorld helloWorld = nettyRpcProxyService.createProxy(IHelloWorld.class); int serverId=18001; NettyRpcContextHolderObject rpcContextHolderObject = new NettyRpcContextHolderObject(NettyGameTypeEnum.WORLD, serverId); NettyRpcContextHolder.setContextHolder(rpcContextHolderObject); String result = helloWorld.getHelloWorld(5); logger.info(result); } public void setTear(){ if (nettyRpcProxyService != null) { try { nettyRpcProxyService.shutdown(); } catch (Exception e) { e.printStackTrace(); } } } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/rpc/zookeeper/NettyZookeeperTest.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.rpc.zookeeper; import com.twjitm.TestSpring; import com.twjitm.core.bootstrap.Bootstrap; import com.twjitm.core.common.zookeeper.NettyZookeeperNodeInfo; import com.twjitm.core.common.zookeeper.NettyZookeeperNodeNettyGameTypeEnum; import com.twjitm.core.common.zookeeper.NettyZookeeperRpcServiceDiscoveryService; import com.twjitm.core.common.zookeeper.NettyZookeeperRpcServiceRegistryService; import com.twjitm.core.spring.SpringServiceManager; import java.util.List; /** * @author twjitm - [Created on 2018-08-23 11:48] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class NettyZookeeperTest { private static NettyZookeeperRpcServiceRegistryService registryService; private static NettyZookeeperRpcServiceDiscoveryService discoveryService; public static void main(String[] args) { TestSpring.initSpring(); Bootstrap.startServer(); registryService = SpringServiceManager.getSpringLoadService().getNettyZookeeperRpcServiceRegistryService(); discoveryService = SpringServiceManager.getSpringLoadService().getNettyZookeeperRpcServiceDiscoveryService(); test(); } private static void test() { List list = discoveryService.getNodeList(NettyZookeeperNodeNettyGameTypeEnum.WORLD); System.out.println(list); } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/rts/LobbySever.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.rts; 2 | 3 | 4 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/server/TestServiceHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.server; 2 | 3 | /** 4 | * Created by on 2018/5/16. 5 | */ 6 | public class TestServiceHandler { 7 | } 8 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/test/TestHashMap.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.test; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.twjitm.core.player.dao.PlayerDao; 5 | 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | /** 10 | * Created by twjitm on 2018/6/7. 11 | */ 12 | public class TestHashMap { 13 | public static void main(String[] args) { 14 | System.out.println(teste("a","b",new String[]{"c","b","ddddd"})); 15 | System.out.println(teste("a","b",new Object[]{new User(),"b","ddddd"})); 16 | } 17 | 18 | public static String teste(String a, String b, Object[] objects) { 19 | 20 | Map map = new HashMap<>(); 21 | map.put(a, a); 22 | map.put(b, b); 23 | map.put("c", objects); 24 | String result=JSON.toJSONString(map); 25 | 26 | Object result2 = JSON.toJSON(map); 27 | System.out.println(result2.getClass().getName()); 28 | System.out.println(result2.toString()); 29 | return result; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/test/User.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.test; 2 | 3 | /** 4 | * @author by twjitm on 2018/11/15/12:02 5 | */ 6 | public class User { 7 | 8 | 9 | private String name; 10 | private int age; 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public void setName(String name) { 17 | this.name = name; 18 | } 19 | 20 | public int getAge() { 21 | return age; 22 | } 23 | 24 | public void setAge(int age) { 25 | this.age = age; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/thread/Test.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.thread; import java.util.concurrent.*; /** * @author twjitm - [Created on 2018-08-21 20:42] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class Test { private final ExecutorService executorService; public Test(ExecutorService executorService) { this.executorService = executorService; } public void test() { CompletionService completionService = new ExecutorCompletionService(executorService); try { Object obj = completionService.submit(new Callable() { @Override public Object call() throws Exception { Thread.sleep(4000l); return "hahaha"; } }).get(2000l, TimeUnit.MILLISECONDS); System.out.println(obj); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); System.out.println("超时了--线程任务"); } } public static void main(String[] args) { ExecutorService executorService = new ThreadPoolExecutor(4, 10, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(10)); Test t = new Test(executorService); t.test(); } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/threads/InputThreadTest.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.threads; 2 | 3 | public class InputThreadTest implements Runnable { 4 | String name; 5 | Object prev; 6 | Object self; 7 | 8 | public InputThreadTest(String name, Object prev, Object self) { 9 | this.name = name; 10 | this.prev = prev; 11 | this.self = self; 12 | } 13 | 14 | @Override 15 | public void run() { 16 | int cout = 0; 17 | while (cout < 10) { 18 | synchronized (prev) { 19 | synchronized (self) { 20 | cout++; 21 | System.out.print(name); 22 | self.notify(); 23 | } 24 | try { 25 | prev.wait(); 26 | } catch (InterruptedException e) { 27 | e.printStackTrace(); 28 | } 29 | } 30 | } 31 | } 32 | 33 | public static void main(String[] args) throws InterruptedException { 34 | Object a = new Object(); 35 | Object b = new Object(); 36 | Object c = new Object(); 37 | InputThreadTest threadTesta = new InputThreadTest("A", c, a); 38 | InputThreadTest threadTestb = new InputThreadTest("B", a, b); 39 | InputThreadTest threadTestc = new InputThreadTest("C", b, c); 40 | new Thread(threadTesta).start(); 41 | Thread.sleep(100); 42 | new Thread(threadTestb).start(); 43 | Thread.sleep(100); 44 | new Thread(threadTestc).start(); 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/threads/ThreadTest.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.threads; 2 | 3 | /** 4 | * Created by 文江 on 2018/5/21. 5 | */ 6 | public class ThreadTest implements Runnable { 7 | @Override 8 | public void run() { 9 | System.out.println("子线程开始执行"); 10 | for (int i = 0; i < 10; i++) { 11 | /* try { 12 | // Thread.currentThread().sleep(1000); 13 | } catch (InterruptedException e) { 14 | e.printStackTrace(); 15 | }*/ 16 | System.out.println(i); 17 | } 18 | System.out.println("子线程结束执行"); 19 | } 20 | 21 | public static void main(String[] args) { 22 | System.out.println("主线程开始"); 23 | ThreadTest threadTest = new ThreadTest(); 24 | threadTest.run(); 25 | Thread2 thread2 = new Thread2(); 26 | thread2.start(); 27 | try { 28 | thread2.join(); 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | System.out.println("主线程结束"); 33 | } 34 | 35 | static class Thread2 extends Thread { 36 | @Override 37 | public void run() { 38 | System.out.println(Thread.currentThread().getName() + " 线程运行开始!"); 39 | for (int i = 0; i < 5; i++) { 40 | System.out.println("子线程" + Thread.currentThread().getName() + "运行 : " + i); 41 | try { 42 | sleep((int) Math.random() * 10); 43 | } catch (InterruptedException e) { 44 | e.printStackTrace(); 45 | } 46 | } 47 | System.out.println(Thread.currentThread().getName() + " 线程运行结束!"); 48 | 49 | } 50 | } 51 | } 52 | --------------------------------------------------------------------------------
13 | * UPD协议编码工厂 14 | * @jdk java version "1.8.0_77" 15 | */ 16 | @Service 17 | public class NettyNetProtoBufUdpMessageEncoderFactory implements INettyNetProtoBufUdpMessageEncoderFactory { 18 | @Override 19 | public ByteBuf createByteBuf(AbstractNettyNetProtoBufMessage netMessage) throws Exception { 20 | ByteBuf byteBuf = Unpooled.buffer(256); 21 | //编写head 22 | NettyUDPMessageHead netMessageHead = (NettyUDPMessageHead) netMessage.getNetMessageHead(); 23 | byteBuf.writeShort(netMessageHead.getHead()); 24 | //长度 25 | byteBuf.writeInt(0); 26 | //设置内容 27 | byteBuf.writeByte(netMessageHead.getVersion()); 28 | byteBuf.writeShort(netMessageHead.getCmd()); 29 | byteBuf.writeInt(netMessageHead.getSerial()); 30 | //设置tockent 31 | byteBuf.writeLong(netMessageHead.getPlayerId()); 32 | byteBuf.writeInt(netMessageHead.getTocken()); 33 | 34 | //编写body 35 | netMessage.encodeNetProtoBufMessageBody(); 36 | NettyNetMessageBody netMessageBody = netMessage.getNetMessageBody(); 37 | byteBuf.writeBytes(netMessageBody.getBytes()); 38 | 39 | //重新设置长度 40 | int skip = 6; 41 | int length = byteBuf.readableBytes() - skip; 42 | byteBuf.setInt(2, length); 43 | byteBuf.slice(); 44 | return byteBuf; 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/AbstractNettyNetMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity; 2 | 3 | import java.util.concurrent.ConcurrentHashMap; 4 | 5 | /** 6 | * Created by 文江 on 2017/11/15. 7 | */ 8 | public abstract class AbstractNettyNetMessage implements INettyMessage { 9 | public NettyNetMessageHead nettyNetMessageHead; 10 | public NettyNetMessageBody nettyNetMessageBody; 11 | /** 12 | * 增加默认属性(附带逻辑调用需要的属性) 13 | */ 14 | private final ConcurrentHashMap attributes = new ConcurrentHashMap(3); 15 | 16 | 17 | public NettyNetMessageHead getNettyNetMessageHead() { 18 | return nettyNetMessageHead; 19 | } 20 | 21 | public void setNettyNetMessageHead(NettyNetMessageHead nettyNetMessageHead) { 22 | this.nettyNetMessageHead = nettyNetMessageHead; 23 | } 24 | 25 | public NettyNetMessageBody getNettyNetMessageBody() { 26 | return nettyNetMessageBody; 27 | } 28 | 29 | public void setNettyNetMessageBody(NettyNetMessageBody nettyNetMessageBody) { 30 | this.nettyNetMessageBody = nettyNetMessageBody; 31 | } 32 | 33 | public void setAttribute(Object key,Object value){ 34 | attributes.put(key,value); 35 | } 36 | 37 | public Object getAttribute(Object key){ 38 | return attributes.get(key); 39 | } 40 | public void remove(Object key){ 41 | attributes.remove(key); 42 | } 43 | 44 | @Override 45 | public String toString() { 46 | return "AbstractNettyNetMessage{" + 47 | "nettyNetMessageHead=" + nettyNetMessageHead + 48 | ", nettyNetMessageBody=" + nettyNetMessageBody + 49 | ", attributes=" + attributes + 50 | '}'; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/AbstractNettyNetProtoBufMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity; 2 | 3 | import com.twjitm.core.common.annotation.MessageCommandAnnotation; 4 | import io.netty.handler.codec.CodecException; 5 | 6 | 7 | /** 8 | * Created by twjitm on 2017/11/15. 9 | * 基础protobuf协议消息 10 | */ 11 | public abstract class AbstractNettyNetProtoBufMessage extends AbstractNettyNetMessage { 12 | 13 | public AbstractNettyNetProtoBufMessage() { 14 | setNettyNetMessageHead(new NettyNetMessageHead()); 15 | setNettyNetMessageBody(new NettyNetMessageBody()); 16 | } 17 | 18 | @Override 19 | public NettyNetMessageHead getNetMessageHead() { 20 | return getNettyNetMessageHead(); 21 | } 22 | 23 | @Override 24 | public NettyNetMessageBody getNetMessageBody() { 25 | return getNettyNetMessageBody(); 26 | } 27 | 28 | protected void initHeadCommId() { 29 | MessageCommandAnnotation messageCommandAnnotation = this.getClass().getAnnotation(MessageCommandAnnotation.class); 30 | if (messageCommandAnnotation != null) { 31 | getNetMessageHead().setCmd((short) messageCommandAnnotation.messageCmd().commId); 32 | } 33 | } 34 | 35 | /** 36 | * 释放message的body 37 | */ 38 | public void releaseMessageBody() throws CodecException, Exception { 39 | getNetMessageBody().setBytes(null); 40 | } 41 | 42 | public abstract void release() throws CodecException; 43 | 44 | public abstract void encodeNetProtoBufMessageBody() throws CodecException, Exception; 45 | 46 | public abstract void decoderNetProtoBufMessageBody() throws CodecException, Exception; 47 | 48 | public void setSerial(int serial) { 49 | getNetMessageHead().setSerial(serial); 50 | } 51 | 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/INettyMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 5 | import com.twjitm.core.common.netstack.entity.NettyNetMessageHead; 6 | 7 | /** 8 | * Created by 文江 on 2017/11/15. 9 | * 基础协议 10 | */ 11 | public interface INettyMessage { 12 | public NettyNetMessageHead getNetMessageHead(); 13 | public NettyNetMessageBody getNetMessageBody(); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/NettyNetMessageBody.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity; 2 | 3 | /** 4 | * Created by 文江 on 2017/11/15. 5 | */ 6 | public class NettyNetMessageBody { 7 | /** 8 | * 存储数据 9 | */ 10 | private byte[] bytes; 11 | 12 | public byte[] getBytes() { 13 | return bytes; 14 | } 15 | 16 | public void setBytes(byte[] bytes) { 17 | this.bytes = bytes; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/NettyNetMessageHead.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity; 2 | 3 | /** 4 | * Created by 文江 on 2017/11/15. 5 | */ 6 | public class NettyNetMessageHead { 7 | 8 | public static final short MESSAGE_HEADER_FLAG = 0x2425; 9 | 10 | /** 11 | * 魔法头 12 | */ 13 | private short head; 14 | /** 15 | * 版本号 16 | */ 17 | private byte version; 18 | /** 19 | * 长度 20 | */ 21 | private int length; 22 | /** 23 | * 命令 24 | */ 25 | private short cmd; 26 | /** 27 | * 序列号 28 | */ 29 | private int serial; 30 | 31 | public NettyNetMessageHead() { 32 | this.head = MESSAGE_HEADER_FLAG; 33 | } 34 | 35 | public short getHead() { 36 | return head; 37 | } 38 | 39 | public void setHead(short head) { 40 | this.head = head; 41 | } 42 | 43 | public byte getVersion() { 44 | return version; 45 | } 46 | 47 | public void setVersion(byte version) { 48 | this.version = version; 49 | } 50 | 51 | public int getLength() { 52 | return length; 53 | } 54 | 55 | public void setLength(int length) { 56 | this.length = length; 57 | } 58 | 59 | public short getCmd() { 60 | return cmd; 61 | } 62 | 63 | public void setCmd(short cmd) { 64 | this.cmd = cmd; 65 | } 66 | 67 | public int getSerial() { 68 | return serial; 69 | } 70 | 71 | public void setSerial(int serial) { 72 | this.serial = serial; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/NettyNetProtoBufMessageBody.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity; 2 | 3 | import com.google.protobuf.AbstractMessage; 4 | 5 | /** 6 | * Created by 文江 on 2017/11/15. 7 | */ 8 | public class NettyNetProtoBufMessageBody extends NettyNetMessageBody{ 9 | //将字节读取为protobuf的抽象对象 10 | private AbstractMessage abstractMessage; 11 | 12 | public AbstractMessage getAbstractMessage() { 13 | return abstractMessage; 14 | } 15 | 16 | public void setAbstractMessage(AbstractMessage abstractMessage) { 17 | this.abstractMessage = abstractMessage; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/http/AbstractNettyNetProtoBufHttpMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.http; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 5 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 6 | 7 | /** 8 | * Created by 文江 on 2017/11/16. 9 | * 抽象http请求消息 10 | */ 11 | public abstract class AbstractNettyNetProtoBufHttpMessage extends AbstractNettyNetProtoBufMessage { 12 | public AbstractNettyNetProtoBufHttpMessage(){ 13 | super(); 14 | setNettyNetMessageHead(new NettyNetHttpMessageHead()); 15 | setNettyNetMessageBody(new NettyNetMessageBody()); 16 | initHeadCommId(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/http/NettyNetHttpMessageHead.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.http; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.NettyNetMessageHead; 5 | 6 | /** 7 | * Created by 文江 on 2017/11/16. 8 | * http协议头 9 | */ 10 | public class NettyNetHttpMessageHead extends NettyNetMessageHead { 11 | private long playerId; 12 | private String token = ""; 13 | 14 | public long getPlayerId() { 15 | return playerId; 16 | } 17 | 18 | public void setPlayerId(long playerId) { 19 | this.playerId = playerId; 20 | } 21 | 22 | public String getToken() { 23 | return token; 24 | } 25 | 26 | public void setToken(String token) { 27 | this.token = token; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/rpc/NettyRpcRequestMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.rpc; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: 文江 Date: 2018/8/19 Time: 10:10 6 | * https://blog.csdn.net/baidu_23086307 7 | */ 8 | public class NettyRpcRequestMessage { 9 | /** 10 | * 请求id 11 | */ 12 | private String requestId; 13 | /** 14 | * class 名 15 | */ 16 | private String className; 17 | /** 18 | * 方法名 19 | */ 20 | private String methodName; 21 | /** 22 | * 请求参数类型 23 | */ 24 | private Class>[] parameterTypes; 25 | /** 26 | * 请求参数 27 | */ 28 | private Object[] parameters; 29 | 30 | public String getRequestId() { 31 | return requestId; 32 | } 33 | 34 | public void setRequestId(String requestId) { 35 | this.requestId = requestId; 36 | } 37 | 38 | public String getClassName() { 39 | return className; 40 | } 41 | 42 | public void setClassName(String className) { 43 | this.className = className; 44 | } 45 | 46 | public String getMethodName() { 47 | return methodName; 48 | } 49 | 50 | public void setMethodName(String methodName) { 51 | this.methodName = methodName; 52 | } 53 | 54 | public Class>[] getParameterTypes() { 55 | return parameterTypes; 56 | } 57 | 58 | public void setParameterTypes(Class>[] parameterTypes) { 59 | this.parameterTypes = parameterTypes; 60 | } 61 | 62 | public Object[] getParameters() { 63 | return parameters; 64 | } 65 | 66 | public void setParameters(Object[] parameters) { 67 | this.parameters = parameters; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/rpc/NettyRpcResponseMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.rpc; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: 文江 Date: 2018/8/19 Time: 10:15 6 | * https://blog.csdn.net/baidu_23086307 7 | */ 8 | public class NettyRpcResponseMessage { 9 | /** 10 | * 请求id 11 | */ 12 | private String requestId; 13 | /** 14 | * 错误码 15 | */ 16 | private String error; 17 | /** 18 | * 返回值 19 | */ 20 | private Object result; 21 | 22 | public String getRequestId() { 23 | return requestId; 24 | } 25 | 26 | public String getError() { 27 | return error; 28 | } 29 | 30 | public Object getResult() { 31 | return result; 32 | } 33 | 34 | public void setRequestId(String requestId) { 35 | this.requestId = requestId; 36 | } 37 | 38 | public void setError(String error) { 39 | this.error = error; 40 | } 41 | 42 | public void setResult(Object result) { 43 | this.result = result; 44 | } 45 | public boolean isError() { 46 | return error != null; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/tcp/AbstractNettyNetProtoBufTcpMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.tcp; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 5 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 6 | import com.twjitm.core.common.netstack.entity.NettyNetMessageHead; 7 | 8 | /** 9 | * Created by 文江 on 2017/11/15. 10 | */ 11 | public abstract class AbstractNettyNetProtoBufTcpMessage extends AbstractNettyNetProtoBufMessage { 12 | public AbstractNettyNetProtoBufTcpMessage() { 13 | super(); 14 | setNettyNetMessageHead(new NettyNetMessageHead()); 15 | setNettyNetMessageBody(new NettyNetMessageBody()); 16 | initHeadCommId(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/tcp/NettyTCPMessageBody.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.tcp; 2 | 3 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 4 | 5 | /** 6 | * Created by 文江 on 2017/11/15. 7 | */ 8 | public class NettyTCPMessageBody extends NettyNetMessageBody { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/tcp/NettyTCPMessageHead.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.tcp; 2 | 3 | import com.twjitm.core.common.netstack.entity.NettyNetMessageHead; 4 | 5 | /** 6 | * Created by 文江 on 2017/11/15. 7 | */ 8 | public class NettyTCPMessageHead extends NettyNetMessageHead { 9 | public NettyTCPMessageHead() { 10 | super(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/udp/AbstractNettyNetProtoBufUdpMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.udp; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 5 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 6 | 7 | import java.net.InetSocketAddress; 8 | 9 | /** 10 | * Created by twjtim on 2017/2/16. 11 | * 抽象的udp消息 12 | */ 13 | public abstract class AbstractNettyNetProtoBufUdpMessage extends AbstractNettyNetProtoBufMessage { 14 | /** 15 | * 发送方 16 | */ 17 | private InetSocketAddress send; 18 | /** 19 | * 接收方 20 | */ 21 | private InetSocketAddress receive; 22 | 23 | 24 | public InetSocketAddress getSend() { 25 | return send; 26 | } 27 | 28 | public void setSend(InetSocketAddress send) { 29 | this.send = send; 30 | } 31 | 32 | public InetSocketAddress getReceive() { 33 | return receive; 34 | } 35 | 36 | public void setReceive(InetSocketAddress receive) { 37 | this.receive = receive; 38 | } 39 | 40 | public AbstractNettyNetProtoBufUdpMessage(){ 41 | super(); 42 | setNettyNetMessageHead(new NettyUDPMessageHead()); 43 | setNettyNetMessageBody(new NettyNetMessageBody()); 44 | initHeadCommId(); 45 | } 46 | 47 | public void setPlayerId(long playerId) { 48 | NettyUDPMessageHead netUdpMessageHead = (NettyUDPMessageHead) getNetMessageHead(); 49 | netUdpMessageHead.setPlayerId(playerId); 50 | } 51 | 52 | public void setTocken(int tocken){ 53 | NettyUDPMessageHead netUdpMessageHead = (NettyUDPMessageHead) getNetMessageHead(); 54 | netUdpMessageHead.setTocken(tocken); 55 | } 56 | 57 | public long getPlayerId(){ 58 | NettyUDPMessageHead netUdpMessageHead = (NettyUDPMessageHead) getNetMessageHead(); 59 | return netUdpMessageHead.getPlayerId(); 60 | } 61 | 62 | public int getTocken(){ 63 | NettyUDPMessageHead netUdpMessageHead = (NettyUDPMessageHead) getNetMessageHead(); 64 | return netUdpMessageHead.getTocken(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/udp/NettyUDPMessageHead.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.udp; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.NettyNetMessageHead; 5 | 6 | /** 7 | * Created by 文江 on 2017/11/15. 8 | */ 9 | public class NettyUDPMessageHead extends NettyNetMessageHead { 10 | private long playerId; 11 | private int tocken; 12 | 13 | public long getPlayerId() { 14 | return playerId; 15 | } 16 | 17 | public void setPlayerId(long playerId) { 18 | this.playerId = playerId; 19 | } 20 | 21 | public int getTocken() { 22 | return tocken; 23 | } 24 | 25 | public void setTocken(int tocken) { 26 | this.tocken = tocken; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/entity/udp/NettyUDpMessageBody.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.entity.udp; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.NettyNetMessageBody; 5 | 6 | /** 7 | * Created by 文江 on 2017/11/15. 8 | */ 9 | public class NettyUDpMessageBody extends NettyNetMessageBody { 10 | private long playerId; 11 | private int tocken; 12 | 13 | public long getPlayerId() { 14 | return playerId; 15 | } 16 | 17 | public void setPlayerId(long playerId) { 18 | this.playerId = playerId; 19 | } 20 | 21 | public int getTocken() { 22 | return tocken; 23 | } 24 | 25 | public void setTocken(int tocken) { 26 | this.tocken = tocken; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/pipeline/INettyServerPipeLine.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.pipeline; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import io.netty.channel.Channel; 5 | 6 | /** 7 | * 管道消息分发器。 管道消息分发器,主要是讲tcp消息或者rpc消息,udp消息以及http消息 8 | * 进行分发,由实现类自己完成实现, 9 | * 10 | * @author twjitm - [Created on 2018-08-02 20:39] 11 | * @company https://github.com/twjitm/ 12 | * @jdk java version "1.8.0_77" 13 | */ 14 | public interface INettyServerPipeLine { 15 | /** 16 | * 分发器 17 | * 18 | * @param channel 19 | * @param message 20 | */ 21 | void dispatch(Channel channel, AbstractNettyNetMessage message); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/sender/INetMessageSender.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.sender; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-07-24 16:23] 7 | * 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public interface INetMessageSender { 11 | 12 | /** 13 | * 14 | * 15 | * @param abstractNettyNetMessage 16 | * @return 17 | */ 18 | public boolean sendMessage(AbstractNettyNetMessage abstractNettyNetMessage); 19 | 20 | /** 21 | * 22 | */ 23 | public void close(); 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/sender/NettyNetTcpMessageSender.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.sender; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import com.twjitm.core.common.netstack.session.NettySession; 5 | import com.twjitm.core.utils.logs.LoggerUtils; 6 | import io.netty.channel.Channel; 7 | import org.apache.log4j.Logger; 8 | 9 | /** 10 | * @author twjitm - [Created on 2018-07-24 16:32] 11 | * @jdk java version "1.8.0_77" 12 | * TCP消息发送器 13 | */ 14 | public class NettyNetTcpMessageSender implements INetMessageSender { 15 | private final NettySession nettySession; 16 | private Logger logger = LoggerUtils.getLogger(this.getClass()); 17 | 18 | public NettyNetTcpMessageSender(NettySession nettySession) { 19 | this.nettySession = nettySession; 20 | } 21 | 22 | @Override 23 | public boolean sendMessage(AbstractNettyNetMessage abstractNettyNetMessage) { 24 | try { 25 | nettySession.write(abstractNettyNetMessage); 26 | } catch (Exception e) { 27 | e.printStackTrace(); 28 | logger.error(e.toString()); 29 | } 30 | return true; 31 | } 32 | 33 | @Override 34 | public void close() { 35 | Channel channel = nettySession.channel; 36 | if (channel.isActive()) { 37 | channel.close(); 38 | } else { 39 | channel.close(); 40 | 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/sender/NettyNetUdpMessageSender.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.sender; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import com.twjitm.core.common.netstack.session.NettySession; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-08-09 16:35] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | * udp协议消息发送器 11 | */ 12 | public class NettyNetUdpMessageSender implements INetMessageSender { 13 | private final NettySession nettySession; 14 | 15 | public NettyNetUdpMessageSender(NettySession nettySession) { 16 | this.nettySession = nettySession; 17 | } 18 | 19 | 20 | @Override 21 | public boolean sendMessage(AbstractNettyNetMessage abstractNettyNetMessage) { 22 | try { 23 | nettySession.write(abstractNettyNetMessage); 24 | } catch (Exception e) { 25 | e.printStackTrace(); 26 | return false; 27 | } 28 | return true; 29 | } 30 | 31 | @Override 32 | public void close() { 33 | nettySession.channel.close(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/session/ISession.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.session; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-07-24 15:55] 7 | * @jdk java version "1.8.0_77"\ 8 | * session��ҵ���� 9 | */ 10 | public interface ISession { 11 | /** 12 | * �жϵ�ǰ�Ự�Ƿ�������״̬ 13 | * 14 | * @return 15 | */ 16 | public boolean isConnected(); 17 | 18 | /** 19 | * @param msg 20 | */ 21 | public void write(AbstractNettyNetMessage msg) throws Exception; 22 | 23 | /** 24 | * 25 | */ 26 | public void close(boolean immediately); 27 | 28 | /** 29 | * �����쳣ʱ�Ƿ�ر����� 30 | * 31 | * @return 32 | */ 33 | public boolean closeOnException(); 34 | 35 | public void write(byte[] msg) throws Exception; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/session/NettySession.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.session; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import io.netty.channel.Channel; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-07-24 15:56] 8 | * @jdk java version "1.8.0_77" 9 | * 自定义session 10 | */ 11 | public abstract class NettySession implements ISession { 12 | public volatile Channel channel; 13 | private long playerId; 14 | 15 | 16 | public NettySession(Channel channel) { 17 | this.channel = channel; 18 | } 19 | 20 | @Override 21 | public boolean isConnected() { 22 | if (channel != null) { 23 | return channel.isActive(); 24 | } 25 | return false; 26 | } 27 | 28 | @Override 29 | public void write(AbstractNettyNetMessage msg) throws Exception { 30 | if (msg != null) { 31 | try { 32 | //防止客户端被重置 33 | if (channel.isActive()) { 34 | channel.writeAndFlush(msg); 35 | } 36 | } catch (Exception e) { 37 | throw new Exception(); 38 | } 39 | 40 | } 41 | } 42 | 43 | @Override 44 | public void close(boolean immediately) { 45 | if (channel != null) { 46 | channel.close(); 47 | } 48 | } 49 | 50 | @Override 51 | public boolean closeOnException() { 52 | return false; 53 | } 54 | 55 | @Override 56 | public void write(byte[] msg) throws Exception { 57 | if (channel != null) { 58 | try { 59 | channel.writeAndFlush(msg); 60 | } catch (Exception e) { 61 | throw new Exception(e); 62 | } 63 | } 64 | } 65 | 66 | public long getPlayerId() { 67 | return playerId; 68 | } 69 | 70 | public void setPlayerId(long playerId) { 71 | this.playerId = playerId; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/netstack/session/udp/NettyUdpSession.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.netstack.session.udp; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import com.twjitm.core.common.netstack.sender.NettyNetUdpMessageSender; 5 | import com.twjitm.core.common.netstack.session.NettySession; 6 | import io.netty.channel.Channel; 7 | 8 | /** 9 | * @author twjitm - [Created on 2018-07-24 15:59] 10 | * @company https://github.com/twjitm/ 11 | * @jdk java version "1.8.0_77" 12 | */ 13 | public class NettyUdpSession extends NettySession { 14 | private NettyNetUdpMessageSender udpMessageSender; 15 | 16 | public NettyUdpSession(Channel channel) { 17 | super(channel); 18 | this.udpMessageSender = new NettyNetUdpMessageSender(this); 19 | } 20 | 21 | @Override 22 | public void write(AbstractNettyNetMessage msg) throws Exception { 23 | if (msg != null) { 24 | if (channel.isActive()) { 25 | channel.writeAndFlush(msg); 26 | } 27 | 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/process/IMessageProcessor.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.process; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 4 | import com.twjitm.core.common.netstack.entity.tcp.AbstractNettyNetProtoBufTcpMessage; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-08-06 20:43] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | */ 11 | public interface IMessageProcessor { 12 | /** 13 | * 启动消息处理器 14 | */ 15 | public void startup(); 16 | 17 | /** 18 | * 停止消息处理器 19 | */ 20 | public void shutdown(); 21 | 22 | /** 23 | * 向消息队列投递消息 24 | * 25 | * @param msg 26 | */ 27 | public void put(AbstractNettyNetMessage msg); 28 | 29 | /** 30 | * 判断队列是否已经达到上限了 31 | * @return 32 | */ 33 | public boolean isFull(); 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/process/tcp/INettyTcpNetProtoMessageProcess.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.process.tcp; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-07-24 15:46] 5 | * @jdk java version "1.8.0_77" 6 | */ 7 | 8 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 9 | 10 | /** 11 | * 12 | */ 13 | public interface INettyTcpNetProtoMessageProcess { 14 | public void processNetMessage(); 15 | public void addNetMessage(AbstractNettyNetMessage abstractNettyNetMessage); 16 | public void close(); 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/process/tcp/ITcpMessageProcessor.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.process.tcp; 2 | 3 | import com.twjitm.core.common.process.IMessageProcessor; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-08-06 20:44] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public interface ITcpMessageProcessor extends IMessageProcessor { 11 | public void putDirectTcpMessage(); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/process/udp/NettyUdpNetProtoMessageProcessor.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.process.udp; 2 | 3 | import com.twjitm.core.common.config.global.GlobalConstants; 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 5 | import com.twjitm.core.common.process.IMessageProcessor; 6 | import com.twjitm.core.utils.logs.LoggerUtils; 7 | import org.apache.log4j.Logger; 8 | 9 | /** 10 | * @author twjitm - [Created on 2018-08-08 15:06] 11 | * @company https://github.com/twjitm/ 12 | * @jdk java version "1.8.0_77" 13 | * udp协议消息处理的一种方式:生产者-----消费者模式 14 | */ 15 | public class NettyUdpNetProtoMessageProcessor implements IMessageProcessor { 16 | Logger logger = LoggerUtils.getLogger(NettyUdpNetProtoMessageProcessor.class); 17 | /** 18 | * 消息处理:服务器系统消息 19 | */ 20 | private IMessageProcessor mainMessageProcessor; 21 | 22 | 23 | public NettyUdpNetProtoMessageProcessor(IMessageProcessor mainMessageProcessor) { 24 | this.mainMessageProcessor = mainMessageProcessor; 25 | } 26 | 27 | @Override 28 | public void startup() { 29 | this.mainMessageProcessor.startup(); 30 | } 31 | 32 | @Override 33 | public void shutdown() { 34 | this.mainMessageProcessor.shutdown(); 35 | } 36 | 37 | /** 38 | * 服务器消息选择处理, 39 | * 玩家消息直接处理 40 | * 41 | * @param msg 42 | */ 43 | @Override 44 | public void put(AbstractNettyNetMessage msg) { 45 | if (!GlobalConstants.GameServiceRuntime.IS_OPEN) { 46 | return; 47 | } 48 | logger.info("放入消息执行队列"+msg.toString()); 49 | this.mainMessageProcessor.put(msg); 50 | } 51 | 52 | @Override 53 | public boolean isFull() { 54 | return this.mainMessageProcessor.isFull(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/ILongId.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-08-08 13:54] 5 | * @company https://github.com/twjitm/ 6 | * @jdk java version "1.8.0_77" 7 | */ 8 | public interface ILongId { 9 | public long getLongId(); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/INettyChannleOperationService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service; 2 | 3 | import com.twjitm.core.common.netstack.session.ISession; 4 | import com.twjitm.core.common.netstack.session.tcp.NettyTcpSession; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-07-26 20:37] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | */ 11 | public interface INettyChannleOperationService { 12 | 13 | public ISession findNettySession(long sessionId); 14 | 15 | public boolean addNettySession(NettyTcpSession session); 16 | 17 | public void removeNettySession(long session); 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/INettyLongFindService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-08-08 14:01] 5 | * @company https://github.com/twjitm/ 6 | * @jdk java version "1.8.0_77" 7 | */ 8 | public interface INettyLongFindService { 9 | /** 10 | * 查找 11 | * @param id 12 | * @return 13 | */ 14 | public T findT(long id); 15 | 16 | /** 17 | * 增加 18 | * @param t 19 | */ 20 | public void addT(T t); 21 | 22 | /** 23 | * 移除 24 | * @param t 25 | * @return 26 | */ 27 | public T removeT(T t); 28 | 29 | /** 30 | * 清除所有 31 | */ 32 | public void clear(); 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/IService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-07-26 20:30] 5 | * @company https://github.com/twjitm/ 6 | * @jdk java version "1.8.0_77" 7 | */ 8 | public interface IService { 9 | public String getId(); 10 | 11 | public void startup() throws Exception; 12 | 13 | public void shutdown() throws Exception; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/Impl/AbstractNettyGamePlayerFindService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.Impl; 2 | 3 | import com.twjitm.core.common.service.ILongId; 4 | import com.twjitm.core.common.service.INettyLongFindService; 5 | import com.twjitm.core.utils.logs.LoggerUtils; 6 | import org.apache.log4j.Logger; 7 | 8 | import java.util.concurrent.ConcurrentHashMap; 9 | 10 | /** 11 | * 维护本地在线玩家集和服务 12 | * 13 | * @author twjitm - [Created on 2018-08-08 14:06] 14 | * @company https://github.com/twjitm/ 15 | * @jdk java version "1.8.0_77" 16 | */ 17 | public abstract class AbstractNettyGamePlayerFindService implements INettyLongFindService { 18 | private Logger logger = LoggerUtils.getLogger(AbstractNettyGamePlayerFindService.class); 19 | private volatile ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<>(); 20 | 21 | @Override 22 | public T findT(long id) { 23 | if (logger.isTraceEnabled()) { 24 | logger.info("NETTY GAME FIND ID =" + id); 25 | } 26 | return concurrentHashMap.get(id); 27 | } 28 | 29 | @Override 30 | public void addT(T t) { 31 | if (logger.isTraceEnabled()) { 32 | logger.info("NETTY GAME ADD ID =" + t.getClass().getSimpleName() + "ID IS" + t.getLongId()); 33 | } 34 | concurrentHashMap.put(t.getLongId(), t); 35 | } 36 | 37 | @Override 38 | public T removeT(T t) { 39 | if (logger.isTraceEnabled()) { 40 | logger.info("NETTY GAME REMOVE ID =" + t.getClass().getSimpleName() + "ID IS" + t.getLongId()); 41 | } 42 | return concurrentHashMap.remove(t.getLongId()); 43 | } 44 | 45 | @Override 46 | public void clear() { 47 | if (logger.isTraceEnabled()) { 48 | logger.info("NETTY GAME CLEAR ALL"); 49 | } 50 | concurrentHashMap.clear(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/Impl/NettyGamePlayerFindServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.Impl; 2 | 3 | import com.twjitm.core.player.entity.GameNettyPlayer; 4 | import org.springframework.stereotype.Service; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-08-08 14:04] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | */ 11 | @Service 12 | public class NettyGamePlayerFindServiceImpl extends AbstractNettyGamePlayerFindService { 13 | 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/Impl/NettyGameServiceConfigServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.Impl; 2 | 3 | import com.twjitm.core.common.service.IService; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-08-16 11:07] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public class NettyGameServiceConfigServiceImpl implements IService { 11 | @Override 12 | public String getId() { 13 | return ""; 14 | } 15 | 16 | @Override 17 | public void startup() throws Exception { 18 | 19 | 20 | 21 | } 22 | 23 | @Override 24 | public void shutdown() throws Exception { 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/http/AsyncNettyHttpHandlerService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.http; 2 | 3 | import com.twjitm.core.common.config.global.GlobalConstants; 4 | import com.twjitm.core.common.service.IService; 5 | import io.netty.util.concurrent.DefaultEventExecutorGroup; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * 10 | * 当业务代码中存在对EventLoop线程阻塞的时候,ChannelPipeline 11 | * 有一些能接收一个EventExecutorGroup的add()方法,如果一个事件 12 | * 被专递给自定义的一个EventExecutorGroup,他将会包含在这个EventExecutorGroup 13 | * 中的某个EventExecutor所处理,从而被Channel本身的EventLoop移除,对于这种用法 14 | * Netty提供了一个种叫做{@link io.netty.util.concurrent.DefaultEventExecutorGroup}的实现 15 | * 其实也是本类主要的一个核心API, 16 | * @author twjitm - [Created on 2018-08-16 12:17] 17 | * @company https://github.com/twjitm/ 18 | * @jdk java version "1.8.0_77" 19 | */ 20 | @Service 21 | public class AsyncNettyHttpHandlerService implements IService { 22 | private DefaultEventExecutorGroup defaultEventExecutorGroup; 23 | 24 | 25 | @Override 26 | public String getId() { 27 | return DefaultEventExecutorGroup.class.getSimpleName(); 28 | } 29 | 30 | @Override 31 | public void startup() throws Exception { 32 | defaultEventExecutorGroup = new DefaultEventExecutorGroup(GlobalConstants.NettyNet.NETTY_NET_HTTP_MESSAGE_THREAD_CORE_NUMBER); 33 | } 34 | 35 | @Override 36 | public void shutdown() throws Exception { 37 | if(defaultEventExecutorGroup != null){ 38 | defaultEventExecutorGroup.shutdownGracefully(); 39 | } 40 | } 41 | 42 | public DefaultEventExecutorGroup getDefaultEventExecutorGroup() { 43 | return defaultEventExecutorGroup; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/client/NettyAsyncRPCCallback.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.client; /** * rpc远程回调接口 * @author twjitm - [Created on 2018-08-20 11:46] * @jdk java version "1.8.0_77" * */ public interface NettyAsyncRPCCallback { void success(Object result); void fail(Exception e); } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/client/NettyRpcContextHolder.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.client; /** * rpc信息上下文持有者 * * @author twjitm - [Created on 2018-08-20 12:28] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class NettyRpcContextHolder { /** * 采用ThreadLocal 模式实现一个线程安全的上下文切换。 */ private static final ThreadLocal contextHolder = new ThreadLocal(); public static NettyRpcContextHolderObject getContext() { return (NettyRpcContextHolderObject) contextHolder.get(); } /** * 通过字符串选择数据源 * * @param */ public static void setContextHolder(NettyRpcContextHolderObject rpcContextHolderObject) { contextHolder.set(rpcContextHolderObject); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/client/NettyRpcContextHolderObject.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.client; import com.twjitm.core.common.enums.NettyGameTypeEnum; /** * rpc上下文持有者对像。主要包含请求信息,服务器信息,请求类型 * 在rpc请求之前需要将基本信息保存到此对象中,底层需要获取基本消息,来路由 * 到具体的远程服务器上。 * * @author twjitm - [Created on 2018-08-20 12:31] * @jdk java version "1.8.0_77" */ public class NettyRpcContextHolderObject { private NettyGameTypeEnum nettyGameTypeEnum; private int serviceId; public NettyRpcContextHolderObject(NettyGameTypeEnum nettyGameTypeEnum, int serviceId) { this.nettyGameTypeEnum = nettyGameTypeEnum; this.serviceId = serviceId; } public NettyGameTypeEnum getNettyGameTypeEnum() { return nettyGameTypeEnum; } public void setNettyGameTypeEnum(NettyGameTypeEnum nettyGameTypeEnum) { this.nettyGameTypeEnum = nettyGameTypeEnum; } public int getServiceId() { return serviceId; } public void setServiceId(int serviceId) { this.serviceId = serviceId; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/client/proxy/INettyAsyncRpcProxy.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.client.proxy; import com.twjitm.core.common.service.rpc.client.NettyRpcFuture; /** * @author twjitm - [Created on 2018-08-20 14:45] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public interface INettyAsyncRpcProxy { public NettyRpcFuture call(String funcName, Object... args); } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/manager/NettyDbRpcConnectManager.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.manager; import com.twjitm.core.common.service.rpc.client.AbstractNettyRpcConnectManager; import org.springframework.stereotype.Service; /** * @author twjitm - [Created on 2018-08-20 13:50] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ @Service public class NettyDbRpcConnectManager extends AbstractNettyRpcConnectManager { } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/manager/NettyGameRpcConnectManager.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.manager; import com.twjitm.core.common.service.rpc.client.AbstractNettyRpcConnectManager; import org.springframework.stereotype.Service; /** * @author twjitm - [Created on 2018-08-20 13:51] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ @Service public class NettyGameRpcConnectManager extends AbstractNettyRpcConnectManager { } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/manager/NettyWorldRpcConnectManager.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.manager; import com.twjitm.core.common.service.rpc.client.AbstractNettyRpcConnectManager; import org.springframework.stereotype.Service; /** * @author twjitm - [Created on 2018-08-20 13:51] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ @Service public class NettyWorldRpcConnectManager extends AbstractNettyRpcConnectManager { } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/serialize/INettyJsonSerializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.serialize; import java.io.IOException; /** * @author twjitm - [Created on 2018-08-22 11:01] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public interface INettyJsonSerializer { public String serialize() throws IOException; public void deserialize(String pack); } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/serialize/INettyRpcSerialize.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.serialize; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: 文江 Date: 2018/8/19 Time: 9:21 6 | * https://blog.csdn.net/baidu_23086307 7 | */ 8 | public interface INettyRpcSerialize { 9 | byte[] serialize(T obj); 10 | 11 | T deserialize(byte[] data, Class cls); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/server/NettyRpcNodeInfo.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.server; /** * @author twjitm - [Created on 2018-08-20 11:03] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class NettyRpcNodeInfo { /** * 服务器id */ private String serverId; /** * 服务ip */ private String host; /** * 端口 */ private String port; public String getServerId() { return serverId; } public void setServerId(String serverId) { this.serverId = serverId; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public int getIntPort(){ return Integer.parseInt(port); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/server/NettySdRpcServiceProvider.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.server; import com.twjitm.core.common.enums.NettyGameTypeEnum; import org.jdom2.DataConversionException; import org.jdom2.Element; import java.util.BitSet; /** * @author twjitm - [Created on 2018-08-20 14:20] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class NettySdRpcServiceProvider { private BitSet bitSet = new BitSet(); public void load(Element element) throws DataConversionException { String boenumString = element.getAttribute("boenum").getValue(); NettyGameTypeEnum boEnum = NettyGameTypeEnum.valueOf(boenumString.toUpperCase()); bitSet.set(boEnum.getBoId(), true); } //是否世界开放 public boolean isWorldOpen(){ return bitSet.get(NettyGameTypeEnum.WORLD.getBoId()); } public boolean isGameOpen(){ return bitSet.get(NettyGameTypeEnum.GAME.getBoId()); } public boolean isDbOpen(){ return bitSet.get(NettyGameTypeEnum.DB.getBoId()); } public boolean validServer(int boId){ return bitSet.get(boId); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/service/rpc/service/NettyRemoteRpcHandlerService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.service.rpc.service; 2 | 3 | import com.twjitm.core.common.config.global.NettyGameServiceConfig; 4 | import com.twjitm.core.common.config.global.NettyGameServiceConfigService; 5 | import com.twjitm.core.common.factory.thread.NettyRpcHandlerThreadPoolFactory; 6 | import com.twjitm.core.common.service.IService; 7 | import com.twjitm.core.spring.SpringServiceManager; 8 | import com.twjitm.threads.utils.ExecutorUtil; 9 | import org.springframework.stereotype.Service; 10 | 11 | /** 12 | * Created by IntelliJ IDEA. 13 | * User: 文江 Date: 2018/8/19 Time: 10:29 14 | * https://blog.csdn.net/baidu_23086307 15 | */ 16 | @Service 17 | public class NettyRemoteRpcHandlerService implements IService { 18 | 19 | private NettyRpcHandlerThreadPoolFactory rpcHandlerThreadPool; 20 | 21 | @Override 22 | public String getId() { 23 | return "NettyRemoteRpcHandlerService"; 24 | } 25 | 26 | @Override 27 | public void startup() throws Exception { 28 | NettyGameServiceConfigService config = SpringServiceManager.getSpringLoadService().getNettyGameServiceConfigService(); 29 | NettyGameServiceConfig gameConfig = config.getNettyGameServiceConfig(); 30 | if (gameConfig.isRpcOpen()) { 31 | //开启服务 32 | rpcHandlerThreadPool= SpringServiceManager.getSpringLoadService(). 33 | getNettyRpcHandlerThreadPoolFactory(); 34 | rpcHandlerThreadPool.createExecutor( 35 | gameConfig.getRpcConnectThreadSize(), 36 | gameConfig.getRpcSendProxyThreadSize()); 37 | } 38 | } 39 | 40 | @Override 41 | public void shutdown() throws Exception { 42 | ExecutorUtil.shutdownAndAwaitTermination(SpringServiceManager.getSpringLoadService().getNettyRpcHandlerThreadPoolFactory().getExecutor()); 43 | } 44 | 45 | public void submit(Runnable runnable) { 46 | if(rpcHandlerThreadPool!=null){ 47 | rpcHandlerThreadPool.getExecutor().submit(runnable); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/system/System.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.system; /** * @author twjitm - [Created on 2018-08-17 10:55] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class System { private SystemType type; private String version; public enum SystemType { LINUX(0, "linux"), WINDOWS(1, "windows"), MAC(2, "mac"); private int value; private String name; SystemType(int value, String name) { this.value = value; this.name = name; } } public SystemType getType() { return type; } public void setType(SystemType type) { this.type = type; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/system/SystemService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.system; import com.twjitm.core.utils.logs.LoggerUtils; import org.apache.log4j.Logger; import java.util.Properties; /** * @author twjitm - [Created on 2018-08-17 10:53] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" * system service */ public class SystemService { private static Logger logger = LoggerUtils.getLogger(SystemService.class); public static System getSystem() { Properties properties = java.lang.System.getProperties(); String os = properties.getProperty("os.name"); System system = new System(); System.SystemType type = null; if (os.contains("windows")) { type = System.SystemType.WINDOWS; } if (os.contains("linux") || os.contains("centos") || os.contains("ubuntu")) { type = System.SystemType.LINUX; } if (os.contains("mac")) { type = System.SystemType.MAC; } system.setVersion(os); system.setType(type); logger.info("OPERATING SYSTEM: " + os); logger.info("JAVA RUNTIME VERSION: " + properties.getProperty("java.runtime.version")); logger.info("JAVA CLASS VERSION: " + properties.getProperty("java.class.version")); logger.info("JAVA VM VERSION: " + properties.getProperty("java.vm.version")); return system; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/update/IUpdatable.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.update; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-07-24 19:56] 5 | * @company https://github.com/twjitm/ 6 | * @jdk java version "1.8.0_77" 7 | */ 8 | public interface IUpdatable { 9 | public boolean update(); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/update/UpdateService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.update; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-08-15 11:06] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public class UpdateService { 11 | 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/common/zookeeper/NettyZookeeperNodeNettyGameTypeEnum.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.common.zookeeper; import com.twjitm.core.common.enums.NettyGameTypeEnum; /** * @author twjitm - [Created on 2018-08-22 10:42] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" * zookeeper 节点枚举 */ public enum NettyZookeeperNodeNettyGameTypeEnum { WORLD(NettyGameTypeEnum.WORLD, "/registry_world_address"), GAME(NettyGameTypeEnum.GAME, "/registry_game_address"), DB(NettyGameTypeEnum.DB, "/registry_db_address"),; private NettyGameTypeEnum nettyGameTypeEnum; private String rootPath; NettyZookeeperNodeNettyGameTypeEnum(NettyGameTypeEnum nettyGameTypeEnum, String rootPath) { this.nettyGameTypeEnum = nettyGameTypeEnum; this.rootPath = rootPath; } public NettyGameTypeEnum getNettyGameTypeEnum() { return nettyGameTypeEnum; } public void setNettyGameTypeEnum(NettyGameTypeEnum nettyGameTypeEnum) { this.nettyGameTypeEnum = nettyGameTypeEnum; } public String getRootPath() { return rootPath; } public void setRootPath(String rootPath) { this.rootPath = rootPath; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/initalizer/NettyHttpMessageServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.initalizer; 2 | 3 | import com.twjitm.core.common.handler.http.NettyNetMessageHttpServerHandler; 4 | import com.twjitm.core.common.service.http.AsyncNettyHttpHandlerService; 5 | import com.twjitm.core.spring.SpringServiceManager; 6 | import io.netty.channel.Channel; 7 | import io.netty.channel.ChannelInitializer; 8 | import io.netty.channel.ChannelPipeline; 9 | import io.netty.channel.socket.SocketChannel; 10 | import io.netty.handler.codec.http.HttpRequestDecoder; 11 | import io.netty.handler.codec.http.HttpResponseEncoder; 12 | 13 | public class NettyHttpMessageServerInitializer extends ChannelInitializer { 14 | @Override 15 | protected void initChannel(SocketChannel socketChannel) throws Exception { 16 | ChannelPipeline channelPipLine = socketChannel.pipeline(); 17 | //use netty self encoder and decoder 18 | channelPipLine.addLast("encoder", new HttpResponseEncoder()); 19 | channelPipLine.addLast("decoder", new HttpRequestDecoder()); 20 | AsyncNettyHttpHandlerService asyncNettyHttpHandlerService = SpringServiceManager.getSpringLoadService().getAsyncNettyHttpHandlerService(); 21 | channelPipLine.addLast(asyncNettyHttpHandlerService.getDefaultEventExecutorGroup(),new NettyNetMessageHttpServerHandler()); 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/initalizer/NettyRpcClientMessageServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.initalizer; import com.twjitm.core.common.handler.rpc.NettyRpcClientServerHandler; import com.twjitm.core.common.netstack.coder.decode.rpc.NettyNetMessageRPCDecoder; import com.twjitm.core.common.netstack.coder.encode.rpc.NettyNetMessageRPCEncoder; import com.twjitm.core.common.netstack.entity.rpc.NettyRpcRequestMessage; import com.twjitm.core.common.netstack.entity.rpc.NettyRpcResponseMessage; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * @author twjitm - [Created on 2018-08-20 11:27] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" * rpc 客戶端登陸 */ public class NettyRpcClientMessageServerInitializer extends ChannelInitializer { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline channelPipeline = socketChannel.pipeline(); int maxLength = Integer.MAX_VALUE; channelPipeline.addLast(new LengthFieldBasedFrameDecoder(maxLength, 0, 4, 0, 0)); channelPipeline.addLast(new NettyNetMessageRPCEncoder(NettyRpcRequestMessage.class)); channelPipeline.addLast(new NettyNetMessageRPCDecoder(NettyRpcResponseMessage.class)); channelPipeline.addLast("logger", new LoggingHandler(LogLevel.DEBUG)); channelPipeline.addLast(new NettyRpcClientServerHandler()); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/initalizer/NettyRpcMessageServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.initalizer; 2 | 3 | import com.twjitm.core.common.config.global.GlobalConstants; 4 | import com.twjitm.core.common.handler.rpc.NettyNetRPCServerHandler; 5 | import com.twjitm.core.common.netstack.coder.decode.rpc.NettyNetMessageRPCDecoder; 6 | import com.twjitm.core.common.netstack.coder.encode.rpc.NettyNetMessageRPCEncoder; 7 | import com.twjitm.core.common.netstack.entity.rpc.NettyRpcRequestMessage; 8 | import com.twjitm.core.common.netstack.entity.rpc.NettyRpcResponseMessage; 9 | import io.netty.channel.ChannelInitializer; 10 | import io.netty.channel.ChannelPipeline; 11 | import io.netty.channel.socket.nio.NioSocketChannel; 12 | import io.netty.handler.codec.LengthFieldBasedFrameDecoder; 13 | import io.netty.handler.logging.LogLevel; 14 | import io.netty.handler.logging.LoggingHandler; 15 | import io.netty.handler.timeout.IdleStateHandler; 16 | 17 | /** 18 | * Created by IntelliJ IDEA. 19 | * User: 文江 Date: 2018/8/19 Time: 10:19 20 | * https://blog.csdn.net/baidu_23086307 21 | */ 22 | public class NettyRpcMessageServerInitializer extends ChannelInitializer { 23 | 24 | @Override 25 | protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception { 26 | ChannelPipeline pipeline = nioSocketChannel.pipeline(); 27 | int maxLength = Integer.MAX_VALUE; 28 | pipeline.addLast("frame", new LengthFieldBasedFrameDecoder(maxLength, 0, 4, 0, 0)); 29 | pipeline.addLast("decoder", new NettyNetMessageRPCDecoder(NettyRpcRequestMessage.class)); 30 | pipeline.addLast("encoder", new NettyNetMessageRPCEncoder(NettyRpcResponseMessage.class)); 31 | int readerIdleTimeSeconds = 0; 32 | int writerIdleTimeSeconds = 0; 33 | int allIdleTimeSeconds = GlobalConstants.NettyNet.SESSION_HEART_ALL_TIMEOUT; 34 | pipeline.addLast("idleStateHandler", new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds)); 35 | pipeline.addLast("logger", new LoggingHandler(LogLevel.DEBUG)); 36 | pipeline.addLast("handler", new NettyNetRPCServerHandler()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/initalizer/NettyTcpMessageServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.initalizer; 2 | 3 | import com.twjitm.core.common.config.global.GlobalConstants; 4 | import com.twjitm.core.common.handler.tcp.NettyNetLoggingHandler; 5 | import com.twjitm.core.common.handler.tcp.NettyNetMessageTcpServerHandler; 6 | import com.twjitm.core.common.netstack.coder.decode.tcp.NettyNetProtoBufMessageTCPDecoder; 7 | import com.twjitm.core.common.netstack.coder.encode.tcp.NettyNetProtoBufMessageTCPEncoder; 8 | import com.twjitm.core.test.TestServiceHandler; 9 | import io.netty.channel.Channel; 10 | import io.netty.channel.ChannelInitializer; 11 | import io.netty.handler.codec.LengthFieldBasedFrameDecoder; 12 | import io.netty.handler.logging.LogLevel; 13 | import io.netty.handler.timeout.IdleStateHandler; 14 | 15 | /** 16 | * Created by 文江 on 2017/11/25. 17 | * TCP协议初始化器 18 | */ 19 | public class NettyTcpMessageServerInitializer extends ChannelInitializer { 20 | @Override 21 | protected void initChannel(Channel ch) throws Exception { 22 | ch.pipeline().addLast("frame", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 2, 4, 0, 0)); 23 | ch.pipeline().addLast(new NettyNetProtoBufMessageTCPDecoder()); 24 | ch.pipeline().addLast(new NettyNetProtoBufMessageTCPEncoder()); 25 | //添加心跳檢測 26 | int readerIdleTimeSeconds = GlobalConstants.NettyNet.SESSION_HEART_READ_TIMEOUT; 27 | int writerIdleTimeSeconds = GlobalConstants.NettyNet.SESSION_HEART_WRITE_TIMEOUT; 28 | int allIdleTimeSeconds = GlobalConstants.NettyNet.SESSION_HEART_ALL_TIMEOUT; 29 | ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds)); 30 | 31 | //ch.pipeline().addLast(new TestServiceHandler()); 32 | ch.pipeline().addLast(new NettyNetLoggingHandler(LogLevel.DEBUG)); 33 | ch.pipeline().addLast(new NettyNetMessageTcpServerHandler()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/initalizer/NettyUdpMessageServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.initalizer; 2 | 3 | import com.twjitm.core.common.handler.udp.NettyNetMessageUdpServerHandler; 4 | import com.twjitm.core.common.netstack.coder.decode.udp.NettyNetProtoBufMessageUDPDecoder; 5 | import com.twjitm.core.common.netstack.coder.encode.udp.NettyNetProtoBufMessageUDPEncoder; 6 | import io.netty.channel.ChannelInitializer; 7 | import io.netty.channel.ChannelPipeline; 8 | import io.netty.channel.socket.nio.NioDatagramChannel; 9 | import io.netty.handler.codec.LengthFieldBasedFrameDecoder; 10 | import io.netty.handler.logging.LogLevel; 11 | import io.netty.handler.logging.LoggingHandler; 12 | 13 | /** 14 | * udp协议初始化器 15 | */ 16 | public class NettyUdpMessageServerInitializer extends ChannelInitializer { 17 | @Override 18 | protected void initChannel(NioDatagramChannel ch) throws Exception { 19 | ChannelPipeline channelPipLine = ch.pipeline(); 20 | int maxLength = Integer.MAX_VALUE; 21 | ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(maxLength, 2, 4, 0, 0)); 22 | ch.pipeline().addLast(new NettyNetProtoBufMessageUDPEncoder()); 23 | ch.pipeline().addLast(new NettyNetProtoBufMessageUDPDecoder()); 24 | channelPipLine.addLast("logger", new LoggingHandler(LogLevel.DEBUG)); 25 | channelPipLine.addLast(new NettyNetMessageUdpServerHandler()); 26 | 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/initalizer/NettyWebSocketServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.initalizer; 2 | 3 | 4 | import com.twjitm.core.common.handler.http.HttpRequestHandler; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.ChannelPipeline; 7 | import io.netty.channel.socket.SocketChannel; 8 | import io.netty.handler.codec.http.HttpObjectAggregator; 9 | import io.netty.handler.codec.http.HttpServerCodec; 10 | import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; 11 | import io.netty.handler.stream.ChunkedWriteHandler; 12 | 13 | /** 14 | * Created by 文江 on 2017/9/25. 15 | */ 16 | public class NettyWebSocketServerInitializer extends ChannelInitializer { 17 | @Override 18 | public void initChannel(SocketChannel ch) throws Exception {//2 19 | ChannelPipeline pipeline = ch.pipeline(); 20 | 21 | pipeline.addLast(new HttpServerCodec()); 22 | pipeline.addLast(new HttpObjectAggregator(64 * 1024)); 23 | pipeline.addLast(new ChunkedWriteHandler()); 24 | 25 | pipeline.addLast(new HttpRequestHandler("/ws")); 26 | pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); 27 | 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/player/dao/PlayerDao.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.player.dao; 2 | 3 | /** 4 | * @author twjitm - [Created on 2018-08-08 20:16] 5 | * @company https://github.com/twjitm/ 6 | * @jdk java version "1.8.0_77" 7 | */ 8 | public class PlayerDao { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/player/entity/GameNettyPlayer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.player.entity; 2 | 3 | import com.twjitm.core.common.netstack.sender.NettyNetTcpMessageSender; 4 | import com.twjitm.core.common.service.ILongId; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-08-08 13:52] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | */ 11 | public class GameNettyPlayer implements IGameNettyPlayer, ILongId { 12 | 13 | //玩家id 14 | private long playerId; 15 | //玩家的udp token 16 | private int udpToken; 17 | 18 | private NettyNetTcpMessageSender netTcpMessageSender; 19 | 20 | public GameNettyPlayer(long playerId, int udpToken, NettyNetTcpMessageSender netTcpMessageSender) { 21 | this.playerId = playerId; 22 | this.udpToken = udpToken; 23 | this.netTcpMessageSender = netTcpMessageSender; 24 | } 25 | 26 | @Override 27 | public long getLongId() { 28 | return this.playerId; 29 | } 30 | 31 | @Override 32 | public long getPlayerId() { 33 | return this.playerId; 34 | } 35 | 36 | @Override 37 | public int getPlayerUdpToken() { 38 | return this.udpToken; 39 | } 40 | 41 | @Override 42 | public NettyNetTcpMessageSender getNetTcpMessageSender() { 43 | return this.netTcpMessageSender; 44 | } 45 | 46 | public void setNetTcpMessageSender(NettyNetTcpMessageSender netTcpMessageSender) { 47 | this.netTcpMessageSender = netTcpMessageSender; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/player/entity/IGameNettyPlayer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.player.entity; 2 | 3 | import com.twjitm.core.common.netstack.sender.NettyNetTcpMessageSender; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-08-08 13:55] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public interface IGameNettyPlayer { 11 | public long getPlayerId(); 12 | public int getPlayerUdpToken(); 13 | public NettyNetTcpMessageSender getNetTcpMessageSender(); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/service/dispatcher/IDispatcherService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.service.dispatcher; 2 | 3 | 4 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetMessage; 5 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 6 | import com.twjitm.core.common.netstack.entity.rpc.NettyRpcRequestMessage; 7 | 8 | /** 9 | * Created by twjitm on 2018/4/27. 10 | */ 11 | public interface IDispatcherService { 12 | /** 13 | * 网络消息分发器 14 | * @param message 15 | * @return 16 | */ 17 | public AbstractNettyNetProtoBufMessage dispatcher(AbstractNettyNetMessage message); 18 | 19 | /** 20 | * rpc消息分发器 21 | * @param request 22 | * @return 23 | * @throws Throwable 24 | */ 25 | public Object dispatcher(NettyRpcRequestMessage request) throws Throwable; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/service/rpc/infor.java: -------------------------------------------------------------------------------- 1 | /** * 暴露的远程服务,远程服务RPC,为以其他服务器通过自定义规则来实现远程调用 * 每一个服务类接口必须注解为NettyRpcServiceAnnotation 类型 * 标记为这个类中所有的方法都是用来提供远程RPC调用的。 * NettyRpcServiceAnnotation 必须要标记在实现类上,调用的时候而需要传入 * 实现类的接口名称,否者将发生反射异常。 */ -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/service/rpc/service/HelloWorldImpl.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.service.rpc.service; import com.twjitm.core.common.annotation.NettyRpcServiceAnnotation; import com.twjitm.core.utils.logs.LoggerUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Repository; /** * @author twjitm - [Created on 2018-08-20 10:26] * @jdk java version "1.8.0_77" * 这个地方一定是注入的是业务对象的接口~~~~~~~~~~~~~~~~ */ @NettyRpcServiceAnnotation(IHelloWorld.class) @Repository public class HelloWorldImpl implements IHelloWorld { private Logger logger = LoggerUtils.getLogger(HelloWorldImpl.class); @Override public String getHelloWorld(int number) { StringBuilder builder = new StringBuilder(); for (int i = number; i > 0; i--) { builder.append("helloworld"); builder.append(i); } System.out.println("rpc 远程调用方法成功。。。。。,即将返回给远程客户端调用"); return builder.toString(); } class Task implements Runnable{ @Override public void run() { } } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/service/rpc/service/IHelloWorld.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.service.rpc.service; /** * @author twjitm - [Created on 2018-08-20 10:24] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public interface IHelloWorld { String getHelloWorld(int number); } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/service/user/Impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.service.user.Impl; 2 | 3 | import com.twjitm.core.service.user.UserService; 4 | import org.springframework.stereotype.Service; 5 | 6 | /** 7 | * Created by 文江 on 2018/4/16. 8 | */ 9 | @Service 10 | public class UserServiceImpl implements UserService { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/service/user/UserService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.service.user; 2 | 3 | /** 4 | * Created by 文江 on 2018/4/16. 5 | */ 6 | public interface UserService { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/test/AsyncExecutorService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.test; import com.twjitm.core.player.entity.GameNettyPlayer; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; /** * spring 异步任务 * * @author twjitm - [Created on 2018-08-31 16:45] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ @Service public class AsyncExecutorService { @Async public void saveUser(GameNettyPlayer player){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("async insert db"); } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/test/TestJson.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.test; 2 | 3 | import com.alibaba.fastjson.JSONArray; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** 9 | * @author by twjitm on 2018/11/9/11:35 10 | */ 11 | public class TestJson { 12 | 13 | public static void main(String[] args) { 14 | test(); 15 | } 16 | 17 | private static void test() { 18 | List testlist = new ArrayList<>(); 19 | for (int i = 0; i < 2; i++) { 20 | Text text = new Text(); 21 | text.setContext("hhshah" + i); 22 | text.setIsdefault(true); 23 | text.setLanguage("en"); 24 | testlist.add(text); 25 | } 26 | System.out.println(JSONArray.toJSONString(testlist)); 27 | 28 | 29 | } 30 | 31 | 32 | public static class Text { 33 | private String language; 34 | private String context; 35 | private boolean isdefault; 36 | 37 | public String getLanguage() { 38 | return language; 39 | } 40 | 41 | public void setLanguage(String language) { 42 | this.language = language; 43 | } 44 | 45 | public String getContext() { 46 | return context; 47 | } 48 | 49 | public void setContext(String context) { 50 | this.context = context; 51 | } 52 | 53 | public boolean isIsdefault() { 54 | return isdefault; 55 | } 56 | 57 | public void setIsdefault(boolean isdefault) { 58 | this.isdefault = isdefault; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/test/TestServiceHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.test; 2 | 3 | import com.twjitm.core.common.netstack.entity.AbstractNettyNetProtoBufMessage; 4 | import com.twjitm.core.spring.SpringLoadServiceImpl; 5 | import com.twjitm.core.spring.SpringServiceManager; 6 | import com.twjitm.core.utils.logs.LoggerUtils; 7 | import io.netty.channel.Channel; 8 | import io.netty.channel.ChannelHandlerContext; 9 | import io.netty.channel.ChannelInboundHandlerAdapter; 10 | import org.apache.log4j.Logger; 11 | 12 | import java.util.ArrayList; 13 | import java.util.HashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | 17 | /** 18 | * Created by 文江 on 2018/5/16. 19 | */ 20 | public class TestServiceHandler extends ChannelInboundHandlerAdapter { 21 | Logger logger = LoggerUtils.getLogger(TestServiceHandler.class); 22 | private Map map = new HashMap(); 23 | private List list = new ArrayList(); 24 | private SpringLoadServiceImpl springLoadManager = SpringServiceManager.springLoadService; 25 | 26 | @Override 27 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 28 | super.channelActive(ctx); 29 | logger.info("有新客户端请求建立"); 30 | /* ctx.writeAndFlush("你好,客户端");*/ 31 | } 32 | 33 | @Override 34 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 35 | super.channelRead(ctx, msg); 36 | map.put(ctx.channel().id().asLongText(), ctx.channel()); 37 | System.out.println("hahahahah"); 38 | System.out.println(ctx.channel().remoteAddress() + "->Server :" + msg.toString()); 39 | System.out.println(ctx.channel().id()); 40 | AbstractNettyNetProtoBufMessage message = springLoadManager.getDispatcherService().dispatcher((AbstractNettyNetProtoBufMessage) msg); 41 | /* ctx.channel().writeAndFlush("服务器对大家说的话!"); 42 | for (Channel channel : list) { 43 | channel.writeAndFlush("广播的消息"); 44 | }*/ 45 | /*list.add(ctx.channel()); 46 | ctx.flush();*/ 47 | ctx.writeAndFlush(message); 48 | } 49 | 50 | public void test() { 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/test/TestWorldChatService.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.test; import com.twjitm.core.common.service.IService; import com.twjitm.core.spring.SpringServiceManager; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author twjitm - [Created on 2018-09-20 16:55] */ public class TestWorldChatService implements IService { @Override public String getId() { return null; } @Override public void startup() throws Exception { ExecutorService executorService=Executors.newCachedThreadPool(); executorService.execute(new WorldChatTask()); } @Override public void shutdown() throws Exception { } class WorldChatTask implements Runnable{ @Override public void run() { while (true){ SpringServiceManager.getSpringLoadService().getNettyKafkaProducerListener(); } } } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/utils/logs/LoggerUtils.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.utils.logs; 2 | 3 | import org.apache.log4j.Logger; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-07-18 17:14] 7 | * @jdk java version "1.8.0_77" 8 | */ 9 | public class LoggerUtils { 10 | 11 | public static Logger getLogger(Class clzz) { 12 | return Logger.getLogger(clzz); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/utils/spring/BeanUtils.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.utils.spring; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * @author twjitm - [Created on 2018-07-27 11:03] 10 | * @company https://github.com/twjitm/ 11 | * @jdk java version "1.8.0_77" 12 | */ 13 | @Service 14 | public class BeanUtils implements ApplicationContextAware { 15 | private static ApplicationContext ctx; 16 | @Override 17 | public void setApplicationContext(ApplicationContext arg0)throws BeansException { 18 | ctx = arg0; 19 | } 20 | 21 | public static Object getBean(String beanName) { 22 | if(ctx == null){ 23 | throw new NullPointerException(); 24 | } 25 | return ctx.getBean(beanName); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/utils/time/timer/ExpirationListener.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.utils.time.timer; /** * @author twjitm - [Created on 2018-08-31 10:36] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public interface ExpirationListener { /** * 过期的任务清理 * * @param expireObject */ void expired(E expireObject); } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/utils/time/timer/TimeSlot.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.utils.time.timer; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; /** * 时间槽 * * @author twjitm - [Created on 2018-08-31 10:34] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class TimeSlot { /** * 时间槽id */ private int id; /** * 槽元素 */ private Set elements = new ConcurrentSkipListSet(); public TimeSlot(int id) { this.id = id; } public void add(E e) { elements.add(e); } public boolean remove(E e) { return elements.remove(e); } public Set getElements() { return elements; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TimeSlot timeSlot = (TimeSlot) obj; if (timeSlot.id != id) { return false; } return true; } } -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/utils/uuid/AtomicLimitNumber.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.utils.uuid; 2 | 3 | import java.util.concurrent.atomic.AtomicLong; 4 | 5 | /** 6 | * @author twjitm - [Created on 2018-07-26 20:46] 7 | * @company https://github.com/twjitm/ 8 | * @jdk java version "1.8.0_77" 9 | */ 10 | public class AtomicLimitNumber { 11 | /** 12 | * 原子数量 13 | */ 14 | private AtomicLong atomicLong; 15 | 16 | public AtomicLimitNumber() { 17 | this.atomicLong = new AtomicLong(); 18 | } 19 | 20 | public long increment(){ 21 | return this.atomicLong.incrementAndGet(); 22 | } 23 | 24 | public long decrement(){ 25 | return this.atomicLong.decrementAndGet(); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/utils/uuid/LongIdGenerator.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.utils.uuid; 2 | 3 | 4 | import java.util.concurrent.atomic.AtomicLong; 5 | 6 | /** 7 | * @author twjitm - [Created on 2018-07-24 19:41] 8 | * @company https://github.com/twjitm/ 9 | * @jdk java version "1.8.0_77" 10 | */ 11 | public class LongIdGenerator { 12 | protected AtomicLong id_gen = new AtomicLong(0); 13 | 14 | public long generateId(){ 15 | return id_gen.incrementAndGet(); 16 | } 17 | 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/twjitm/core/zookeeper/Constant.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.core.zookeeper; 2 | 3 | /** 4 | * Created by on 2018/4/17. 5 | * ZOOKEEPER 6 | */ 7 | public class Constant { 8 | public static final int ZK_SESSION_TIMEOUT = 20000; 9 | public static String ZK_REGISTRY_PATH; 10 | public static String ZK_DATA_PATH; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/resources/bean/game-kafka.properties: -------------------------------------------------------------------------------- 1 | kafka.taskThreadSize=4 kafka.corePoolSize=4 kafka.maximumPoolSize=4 kafka.keepAliveTime=5000 -------------------------------------------------------------------------------- /src/main/resources/bean/game-properties.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twjitm/twjitm-core/85f60459c36028b48f1c3b47ee09d67c2befffb1/src/main/resources/bean/game-properties.properties -------------------------------------------------------------------------------- /src/main/resources/bean/game-zookeeper.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twjitm/twjitm-core/85f60459c36028b48f1c3b47ee09d67c2befffb1/src/main/resources/bean/game-zookeeper.properties -------------------------------------------------------------------------------- /src/main/resources/bean/log4j2-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | front.log 14 | d:/usr/front/log/ 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 29 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /src/main/resources/bean/netty-http-config.xml: -------------------------------------------------------------------------------- 1 | http_server 21001 127.0.0.1 11030 false 300 -------------------------------------------------------------------------------- /src/main/resources/bean/netty-rpc-config.xml: -------------------------------------------------------------------------------- 1 | rpc_server 11001 127.0.0.1 11040 -------------------------------------------------------------------------------- /src/main/resources/bean/netty-udp-config.xml: -------------------------------------------------------------------------------- 1 | udp_server 11001 127.0.0.1 11020 1 true -------------------------------------------------------------------------------- /src/main/resources/bean/netty-websocket-config.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/bean/rpc-server-register.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/main/resources/bean/rpc-service-register.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twjitm/twjitm-core/85f60459c36028b48f1c3b47ee09d67c2befffb1/src/main/resources/log4j.properties -------------------------------------------------------------------------------- /src/main/resources/mail/mail.properties: -------------------------------------------------------------------------------- 1 | myEmailAccount=1029718215@qq.com myEmailPassword =twjtim456 mail.transport.protocol=smtp mail.smtp.host=smtp.qq.com mail.smtp.auth=true mail.smtp.starttls.enable=true authCode=yfjcfdumqdaebeee -------------------------------------------------------------------------------- /src/main/resources/proto/LoginOnlineClientTcpMessagebuf.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | message LoginOnlineClientTcpMessage { 3 | int64 player_id = 1; 4 | } -------------------------------------------------------------------------------- /src/main/resources/proto/OnlineClientUdpMessageBuf.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | message OnlineClientUdpMessage { 3 | int64 id = 1; 4 | 5 | 6 | } -------------------------------------------------------------------------------- /src/main/resources/proto/OnlineHeratClientHttpMessageBuf.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | option java_multiple_files = true; 3 | 4 | option java_package = "com.twjitm.core.common.proto"; 5 | 6 | message OnlineClientHttpMessage { 7 | int64 player_id = 1; 8 | string player_name = 2; 9 | 10 | } 11 | 12 | message LoginProxy { 13 | string name = 1; 14 | string password = 2; 15 | } -------------------------------------------------------------------------------- /src/main/resources/proto/build.sh: -------------------------------------------------------------------------------- 1 | # 打包proto脚本,在proto.exe 同级目录下执行 2 | .\protoc.exe --java_out=./ your.proto 3 | .\protoc.exe --csharp_out=./ your.proto 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/main/resources/spring/applicationContext-async-task.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/spring/applicationContext-kafka-producer.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/spring/applicationContext-kafka.consumer.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/spring/applicationContext-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/ClientServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.twjitm; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelOption; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioSocketChannel; 9 | 10 | /** 11 | * Created by twjitm on 2018/5/14. 12 | * netty客户端 13 | */ 14 | public class ClientServiceTest { 15 | static String ip = "127.0.0.1"; 16 | static int port = 11010; 17 | 18 | public static void main(String[] args) { 19 | TestSpring.initSpring(); 20 | startup(ip,port); 21 | } 22 | 23 | 24 | public static void startup(String ip, int port) { 25 | EventLoopGroup eventExecutors = new NioEventLoopGroup(); 26 | Bootstrap bootstrap = new Bootstrap(); 27 | // bootstrap.bind(ip,port); 28 | bootstrap.group(eventExecutors); 29 | bootstrap.channel(NioSocketChannel.class); 30 | bootstrap.option(ChannelOption.TCP_NODELAY, true); 31 | bootstrap.handler(new TestChannelInitializer()); 32 | try { 33 | ChannelFuture future = bootstrap.connect(ip, port).sync(); 34 | future.channel().closeFuture().sync(); 35 | 36 | } catch (InterruptedException e) { 37 | e.printStackTrace(); 38 | } 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/TestChannelInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm; 2 | 3 | import com.twjitm.core.common.netstack.coder.decode.tcp.NettyNetProtoBufMessageTCPDecoder; 4 | import com.twjitm.core.common.netstack.coder.encode.tcp.NettyNetProtoBufMessageTCPEncoder; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.handler.codec.LengthFieldBasedFrameDecoder; 8 | 9 | 10 | /** 11 | * Created by 文江 on 2017/11/13. 12 | */ 13 | public class TestChannelInitializer extends ChannelInitializer { 14 | 15 | protected void initChannel(SocketChannel ch) throws Exception { 16 | 17 | int maxLength = Integer.MAX_VALUE; 18 | ch.pipeline().addLast("frame", new LengthFieldBasedFrameDecoder(maxLength, 2, 4, 0, 0)); 19 | ch.pipeline().addLast(new NettyNetProtoBufMessageTCPEncoder()); 20 | ch.pipeline().addLast(new NettyNetProtoBufMessageTCPDecoder()); 21 | ch.pipeline().addLast(new TestClientHandler()); 22 | } 23 | 24 | 25 | /** 26 | * google proto buffer encode and decode; 27 | */ 28 | 29 | /* @Override 30 | protected void initChannel(SocketChannel ch) { 31 | ChannelPipeline pipeline = ch.pipeline(); 32 | 33 | // ----Protobuf处理器,这里的配置是关键---- 34 | pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());// 用于decode前解决半包和粘包问题(利用包头中的包含数组长度来识别半包粘包) 35 | //配置Protobuf解码处理器,消息接收到了就会自动解码,ProtobufDecoder是netty自带的,Message是自己定义的Protobuf类 36 | pipeline.addLast("protobufDecoder", 37 | new ProtobufDecoder(); 38 | // 用于在序列化的字节数组前加上一个简单的包头,只包含序列化的字节长度。 39 | pipeline.addLast("frameEncoder", 40 | new ProtobufVarint32LengthFieldPrepender()); 41 | //配置Protobuf编码器,发送的消息会先经过编码 42 | pipeline.addLast("protobufEncoder", new ProtobufEncoder()); 43 | 44 | }*/ 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/TestClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm; 2 | 3 | import com.twjitm.core.common.entity.online.LoginOnlineClientTcpMessage; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.ChannelInboundHandlerAdapter; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | /** 10 | * Created by 文江 on 2017/11/13. 11 | */ 12 | public class TestClientHandler extends ChannelInboundHandlerAdapter { 13 | private Logger logger=LoggerFactory.getLogger(TestClientHandler.class); 14 | 15 | public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 16 | 17 | 18 | } 19 | 20 | public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { 21 | 22 | } 23 | 24 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 25 | System.out.println("-----------error--------------"+cause.getMessage()); 26 | ctx.close(); 27 | } 28 | 29 | @Override 30 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 31 | /* System.out.println("into channelActive"); 32 | ChatMessage chatMessage=new ChatMessage(); 33 | chatMessage.setChatType(1); 34 | chatMessage.setContext("twjitm"); 35 | chatMessage.setReceiveHaldUrl("url"); 36 | chatMessage.setRead(true); 37 | chatMessage.setReceiveNickName("haha"); 38 | chatMessage.setReceiveSession("gaga"); 39 | chatMessage.setReceiveUId(11); 40 | ctx.writeAndFlush(chatMessage);*/ 41 | for(int i=0;i<100;i++){ 42 | LoginOnlineClientTcpMessage login=new LoginOnlineClientTcpMessage(); 43 | login.setPlayerId(Long.valueOf(10086)); 44 | ctx.writeAndFlush(login); 45 | logger.info("send message to server................................"); 46 | } 47 | 48 | } 49 | 50 | @Override 51 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 52 | super.channelRead(ctx, msg); 53 | System.out.println(msg.toString()); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/TestSpring.java: -------------------------------------------------------------------------------- 1 | package com.twjitm; 2 | 3 | 4 | import com.twjitm.core.spring.SpringServiceManager; 5 | 6 | public class TestSpring { 7 | public static void initSpring(){ 8 | SpringServiceManager.init(); 9 | SpringServiceManager.start(); 10 | } 11 | 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/books/client/EchoClient.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.books.client; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.SocketChannel; 9 | import io.netty.channel.socket.nio.NioSocketChannel; 10 | 11 | import java.net.InetSocketAddress; 12 | 13 | /** 14 | * 客户端引导 15 | */ 16 | public class EchoClient { 17 | public static void main(String[] args) { 18 | start(8081); 19 | } 20 | 21 | private static void start(int port){ 22 | EventLoopGroup group = new NioEventLoopGroup(); 23 | Bootstrap bootstrap = new Bootstrap(); 24 | 25 | bootstrap.group(group).channel(NioSocketChannel.class) 26 | .remoteAddress(new InetSocketAddress("", port)) 27 | .handler(new ChannelInitializer() { 28 | @Override 29 | protected void initChannel(SocketChannel ch) throws Exception { 30 | ch.pipeline().addLast(new EchoClientHandler()); 31 | } 32 | }); 33 | ChannelFuture future = null; 34 | try { 35 | future = bootstrap.connect().sync(); 36 | } catch (InterruptedException e) { 37 | e.printStackTrace(); 38 | } 39 | try { 40 | future.channel().closeFuture().sync(); 41 | } catch (InterruptedException e) { 42 | e.printStackTrace(); 43 | } 44 | finally { 45 | try { 46 | group.shutdownGracefully().await(); 47 | } catch (InterruptedException e) { 48 | e.printStackTrace(); 49 | } 50 | } 51 | 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/books/client/EchoClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.books.client; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerContext; 6 | import io.netty.channel.SimpleChannelInboundHandler; 7 | import io.netty.util.CharsetUtil; 8 | 9 | /** 10 | * Created by on 2018/5/18. 11 | */ 12 | public class EchoClientHandler extends SimpleChannelInboundHandler { 13 | 14 | @Override 15 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 16 | super.channelActive(ctx); 17 | ctx.writeAndFlush(Unpooled.copiedBuffer("netty rocks", CharsetUtil.UTF_8)); 18 | } 19 | 20 | @Override 21 | protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { 22 | System.out.println("client hdfhdfdfh received"+msg.toString(CharsetUtil.UTF_8)); 23 | } 24 | 25 | @Override 26 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 27 | super.exceptionCaught(ctx, cause); 28 | cause.printStackTrace(); 29 | ctx.close(); 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/books/server/EchoServer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.books.server; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelOption; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioServerSocketChannel; 9 | 10 | /** 11 | * Created by 文江 on 2018/5/18. 12 | */ 13 | public class EchoServer { 14 | private static int port; 15 | 16 | public EchoServer(int port) { 17 | this.port = port; 18 | } 19 | 20 | public static void main(String[] args) { 21 | new EchoServer(8081).start(); 22 | } 23 | 24 | public static void start() { 25 | final EchoServiceHandler echoServiceHandler = new EchoServiceHandler(); 26 | EventLoopGroup group = new NioEventLoopGroup(); 27 | EventLoopGroup listenIntoGroup = new NioEventLoopGroup(); // (1) 28 | EventLoopGroup progressGroup = new NioEventLoopGroup(); 29 | ServerBootstrap b = new ServerBootstrap(); // (2) 30 | b.group(listenIntoGroup, progressGroup) 31 | .channel(NioServerSocketChannel.class) // (3) 32 | .childHandler(echoServiceHandler) //(4) 33 | .option(ChannelOption.SO_BACKLOG, 128) // (5) 34 | .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)*/ 35 | // 绑定端口,开始接收进来的连接 36 | ChannelFuture f = null; // (7) 37 | try { 38 | f = b.bind("127.0.0.1", port).sync(); 39 | System.out.println("服务器启动了"); 40 | f.channel().closeFuture().sync(); 41 | } catch (InterruptedException e) { 42 | e.printStackTrace(); 43 | } finally { 44 | listenIntoGroup.shutdownGracefully(); 45 | progressGroup.shutdownGracefully(); 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/books/server/EchoServiceHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.books.server; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelFutureListener; 6 | import io.netty.channel.ChannelHandler; 7 | import io.netty.channel.ChannelHandlerContext; 8 | import io.netty.channel.ChannelInboundHandlerAdapter; 9 | import io.netty.util.CharsetUtil; 10 | 11 | /** 12 | * Created by 文江 on 2018/5/17. 13 | */ 14 | @ChannelHandler.Sharable 15 | public class EchoServiceHandler extends ChannelInboundHandlerAdapter { 16 | @Override 17 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 18 | ByteBuf byteBuf = (ByteBuf) msg; 19 | System.out.println(byteBuf.toString(CharsetUtil.UTF_8)); 20 | ctx.write(byteBuf); 21 | } 22 | 23 | @Override 24 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 25 | ctx.writeAndFlush(Unpooled.BIG_ENDIAN).addListener(ChannelFutureListener.CLOSE); 26 | } 27 | 28 | @Override 29 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 30 | cause.printStackTrace(); 31 | ctx.close(); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/email/MailMessage.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.email; import java.util.Date; /** * @author twjitm - [Created on 2018-08-24 12:17] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class MailMessage { private String context; private Date date; public String getContext() { return context; } public void setContext(String context) { this.context = context; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/email/User.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.email; import java.util.Date; /** * @author twjitm - [Created on 2018-08-24 12:21] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class User { private long id; private String email; private String password; private String username; private String role; private int status; private Date regTime; private String regIp; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getRegTime() { return regTime; } public void setRegTime(Date regTime) { this.regTime = regTime; } public String getRegIp() { return regIp; } public void setRegIp(String regIp) { this.regIp = regIp; } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/http/GameHttpClientInitializer.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.http; 2 | 3 | import io.netty.channel.ChannelInitializer; 4 | import io.netty.channel.ChannelPipeline; 5 | import io.netty.channel.socket.SocketChannel; 6 | import io.netty.handler.codec.http.HttpRequestEncoder; 7 | import io.netty.handler.codec.http.HttpResponseDecoder; 8 | import io.netty.handler.ssl.SslContext; 9 | 10 | /** 11 | * Created by twjitm on 2017/9/29. 12 | */ 13 | public class GameHttpClientInitializer extends ChannelInitializer { 14 | 15 | private final SslContext sslCtx; 16 | 17 | public GameHttpClientInitializer(SslContext sslCtx) { 18 | this.sslCtx = sslCtx; 19 | } 20 | 21 | @Override 22 | public void initChannel(SocketChannel ch) { 23 | ChannelPipeline p = ch.pipeline(); 24 | if (sslCtx != null) { 25 | p.addLast(sslCtx.newHandler(ch.alloc())); 26 | } 27 | p.addLast("encoder", new HttpRequestEncoder()); 28 | // p.addLast("trunk", new HttpObjectAggregator(1048576)); 29 | p.addLast("decoder", new HttpResponseDecoder()); 30 | 31 | p.addLast(new GameHttpClientHandler()); 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/kafka/TestKafka.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.kafka; import com.twjitm.TestSpring; import com.twjitm.core.common.kafka.KafkaTaskType; import com.twjitm.core.common.kafka.NettyKafkaProducerListener; import com.twjitm.core.spring.SpringServiceManager; import javax.annotation.Resource; /** * @author twjitm - [Created on 2018-09-05 12:25] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class TestKafka { public static void main(String[] args) { TestSpring.initSpring(); test(); } public static void test() { WordChatTask task = new WordChatTask(KafkaTaskType.WORLD_CHAT); task.setValue("世界,你好"); NettyKafkaProducerListener nettyKafkaProducerListener = SpringServiceManager.getSpringLoadService().getNettyKafkaProducerListener(); nettyKafkaProducerListener.put(task); } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/kafka/WordChatTask.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.kafka; import com.twjitm.core.common.kafka.AbstractKafkaPushTask; import com.twjitm.core.common.kafka.KafkaTaskType; /** * @author twjitm - [Created on 2018-09-05 11:52] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class WordChatTask extends AbstractKafkaPushTask { public WordChatTask(KafkaTaskType taskType) { super(taskType); } @Override public void setValue(Object value) { this.value=value; } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/rpc/HelloWorldCallbackTest.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.rpc; import com.twjitm.TestSpring; import com.twjitm.core.common.enums.NettyGameTypeEnum; import com.twjitm.core.common.service.rpc.client.NettyAsyncRPCCallback; import com.twjitm.core.common.service.rpc.client.NettyRpcFuture; import com.twjitm.core.common.service.rpc.client.NettyRpcContextHolder; import com.twjitm.core.common.service.rpc.client.NettyRpcContextHolderObject; import com.twjitm.core.common.service.rpc.client.proxy.INettyAsyncRpcProxy; import com.twjitm.core.common.service.rpc.service.NettyRpcProxyService; import com.twjitm.core.service.rpc.service.IHelloWorld; import com.twjitm.core.spring.SpringServiceManager; /** * @author twjitm - [Created on 2018-08-20 17:26] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" * 异步回调 */ public class HelloWorldCallbackTest { private static NettyRpcProxyService nettyRpcProxyService; public static void main(String[] args) { init(); } private static void init() { TestSpring.initSpring(); nettyRpcProxyService = SpringServiceManager.getSpringLoadService().getNettyRpcProxyService(); INettyAsyncRpcProxy async = nettyRpcProxyService.createAsync(IHelloWorld.class); NettyRpcContextHolderObject rpcContextHolderObject = new NettyRpcContextHolderObject(NettyGameTypeEnum.WORLD, 9001); NettyRpcContextHolder.setContextHolder(rpcContextHolderObject); NettyRpcFuture rpcFuture = async.call("getHelloWorld", 5); rpcFuture.addCallback(new NettyAsyncRPCCallback() { @Override public void success(Object result) { System.out.println(result); } @Override public void fail(Exception e) { System.out.println(e); } }); } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/rpc/HelloWorldServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.rpc; import com.twjitm.TestSpring; import com.twjitm.core.common.enums.NettyGameTypeEnum; import com.twjitm.core.common.service.rpc.client.NettyRpcContextHolder; import com.twjitm.core.common.service.rpc.client.NettyRpcContextHolderObject; import com.twjitm.core.common.service.rpc.service.NettyRpcProxyService; import com.twjitm.core.service.rpc.service.IHelloWorld; import com.twjitm.core.spring.SpringServiceManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author twjitm - [Created on 2018-08-20 15:16] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" * * 同步阻塞调用 */ public class HelloWorldServiceTest { Logger logger=LoggerFactory.getLogger(HelloWorldServiceTest.class); private NettyRpcProxyService nettyRpcProxyService; public static void main(String[] args) { TestSpring.initSpring(); HelloWorldServiceTest helloServiceTest = new HelloWorldServiceTest(); helloServiceTest.init(); helloServiceTest.helloTest1(); helloServiceTest.setTear(); } private void init() { nettyRpcProxyService=SpringServiceManager.getSpringLoadService().getNettyRpcProxyService(); } private void helloTest1() { IHelloWorld helloWorld = nettyRpcProxyService.createProxy(IHelloWorld.class); int serverId=18001; NettyRpcContextHolderObject rpcContextHolderObject = new NettyRpcContextHolderObject(NettyGameTypeEnum.WORLD, serverId); NettyRpcContextHolder.setContextHolder(rpcContextHolderObject); String result = helloWorld.getHelloWorld(5); logger.info(result); } public void setTear(){ if (nettyRpcProxyService != null) { try { nettyRpcProxyService.shutdown(); } catch (Exception e) { e.printStackTrace(); } } } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/rpc/zookeeper/NettyZookeeperTest.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.rpc.zookeeper; import com.twjitm.TestSpring; import com.twjitm.core.bootstrap.Bootstrap; import com.twjitm.core.common.zookeeper.NettyZookeeperNodeInfo; import com.twjitm.core.common.zookeeper.NettyZookeeperNodeNettyGameTypeEnum; import com.twjitm.core.common.zookeeper.NettyZookeeperRpcServiceDiscoveryService; import com.twjitm.core.common.zookeeper.NettyZookeeperRpcServiceRegistryService; import com.twjitm.core.spring.SpringServiceManager; import java.util.List; /** * @author twjitm - [Created on 2018-08-23 11:48] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class NettyZookeeperTest { private static NettyZookeeperRpcServiceRegistryService registryService; private static NettyZookeeperRpcServiceDiscoveryService discoveryService; public static void main(String[] args) { TestSpring.initSpring(); Bootstrap.startServer(); registryService = SpringServiceManager.getSpringLoadService().getNettyZookeeperRpcServiceRegistryService(); discoveryService = SpringServiceManager.getSpringLoadService().getNettyZookeeperRpcServiceDiscoveryService(); test(); } private static void test() { List list = discoveryService.getNodeList(NettyZookeeperNodeNettyGameTypeEnum.WORLD); System.out.println(list); } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/rts/LobbySever.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.rts; 2 | 3 | 4 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/server/TestServiceHandler.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.server; 2 | 3 | /** 4 | * Created by on 2018/5/16. 5 | */ 6 | public class TestServiceHandler { 7 | } 8 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/test/TestHashMap.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.test; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.twjitm.core.player.dao.PlayerDao; 5 | 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | /** 10 | * Created by twjitm on 2018/6/7. 11 | */ 12 | public class TestHashMap { 13 | public static void main(String[] args) { 14 | System.out.println(teste("a","b",new String[]{"c","b","ddddd"})); 15 | System.out.println(teste("a","b",new Object[]{new User(),"b","ddddd"})); 16 | } 17 | 18 | public static String teste(String a, String b, Object[] objects) { 19 | 20 | Map map = new HashMap<>(); 21 | map.put(a, a); 22 | map.put(b, b); 23 | map.put("c", objects); 24 | String result=JSON.toJSONString(map); 25 | 26 | Object result2 = JSON.toJSON(map); 27 | System.out.println(result2.getClass().getName()); 28 | System.out.println(result2.toString()); 29 | return result; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/test/User.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.test; 2 | 3 | /** 4 | * @author by twjitm on 2018/11/15/12:02 5 | */ 6 | public class User { 7 | 8 | 9 | private String name; 10 | private int age; 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public void setName(String name) { 17 | this.name = name; 18 | } 19 | 20 | public int getAge() { 21 | return age; 22 | } 23 | 24 | public void setAge(int age) { 25 | this.age = age; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/thread/Test.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.thread; import java.util.concurrent.*; /** * @author twjitm - [Created on 2018-08-21 20:42] * @company https://github.com/twjitm/ * @jdk java version "1.8.0_77" */ public class Test { private final ExecutorService executorService; public Test(ExecutorService executorService) { this.executorService = executorService; } public void test() { CompletionService completionService = new ExecutorCompletionService(executorService); try { Object obj = completionService.submit(new Callable() { @Override public Object call() throws Exception { Thread.sleep(4000l); return "hahaha"; } }).get(2000l, TimeUnit.MILLISECONDS); System.out.println(obj); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); System.out.println("超时了--线程任务"); } } public static void main(String[] args) { ExecutorService executorService = new ThreadPoolExecutor(4, 10, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(10)); Test t = new Test(executorService); t.test(); } } -------------------------------------------------------------------------------- /src/test/java/com/twjitm/threads/InputThreadTest.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.threads; 2 | 3 | public class InputThreadTest implements Runnable { 4 | String name; 5 | Object prev; 6 | Object self; 7 | 8 | public InputThreadTest(String name, Object prev, Object self) { 9 | this.name = name; 10 | this.prev = prev; 11 | this.self = self; 12 | } 13 | 14 | @Override 15 | public void run() { 16 | int cout = 0; 17 | while (cout < 10) { 18 | synchronized (prev) { 19 | synchronized (self) { 20 | cout++; 21 | System.out.print(name); 22 | self.notify(); 23 | } 24 | try { 25 | prev.wait(); 26 | } catch (InterruptedException e) { 27 | e.printStackTrace(); 28 | } 29 | } 30 | } 31 | } 32 | 33 | public static void main(String[] args) throws InterruptedException { 34 | Object a = new Object(); 35 | Object b = new Object(); 36 | Object c = new Object(); 37 | InputThreadTest threadTesta = new InputThreadTest("A", c, a); 38 | InputThreadTest threadTestb = new InputThreadTest("B", a, b); 39 | InputThreadTest threadTestc = new InputThreadTest("C", b, c); 40 | new Thread(threadTesta).start(); 41 | Thread.sleep(100); 42 | new Thread(threadTestb).start(); 43 | Thread.sleep(100); 44 | new Thread(threadTestc).start(); 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/com/twjitm/threads/ThreadTest.java: -------------------------------------------------------------------------------- 1 | package com.twjitm.threads; 2 | 3 | /** 4 | * Created by 文江 on 2018/5/21. 5 | */ 6 | public class ThreadTest implements Runnable { 7 | @Override 8 | public void run() { 9 | System.out.println("子线程开始执行"); 10 | for (int i = 0; i < 10; i++) { 11 | /* try { 12 | // Thread.currentThread().sleep(1000); 13 | } catch (InterruptedException e) { 14 | e.printStackTrace(); 15 | }*/ 16 | System.out.println(i); 17 | } 18 | System.out.println("子线程结束执行"); 19 | } 20 | 21 | public static void main(String[] args) { 22 | System.out.println("主线程开始"); 23 | ThreadTest threadTest = new ThreadTest(); 24 | threadTest.run(); 25 | Thread2 thread2 = new Thread2(); 26 | thread2.start(); 27 | try { 28 | thread2.join(); 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | System.out.println("主线程结束"); 33 | } 34 | 35 | static class Thread2 extends Thread { 36 | @Override 37 | public void run() { 38 | System.out.println(Thread.currentThread().getName() + " 线程运行开始!"); 39 | for (int i = 0; i < 5; i++) { 40 | System.out.println("子线程" + Thread.currentThread().getName() + "运行 : " + i); 41 | try { 42 | sleep((int) Math.random() * 10); 43 | } catch (InterruptedException e) { 44 | e.printStackTrace(); 45 | } 46 | } 47 | System.out.println(Thread.currentThread().getName() + " 线程运行结束!"); 48 | 49 | } 50 | } 51 | } 52 | --------------------------------------------------------------------------------