Java教程

java游戏服务器——Netty网络服务

本文主要是介绍java游戏服务器——Netty网络服务,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

java游戏服务器架构中,请多多指教——manREDoo

定义消息头

/**
 * <p>
 * 消息头
 * 魔法头short+版本号byte+长度int+协议命令号short+唯一序列号
 * </p>
 *
 * @author : 钟满红
 */
public class MessageHead {
    public static final short MESSAGE_HEADER_FLAG = 0x2425;

    /**
     * 魔法头
     */
    private Short head;
    /**
     * 版本号
     */
    private Integer version;
    /**
     * 长度
     */
    private Integer length;
    /**
     * 命令
     */
    private Integer cmd;
    /**
     * 序列号
     */
    private Integer serial;

    public MessageHead(){
        this.head = MESSAGE_HEADER_FLAG;
    }

    public Short getHead() {
        return head;
    }

    public void setHead(Short head) {
        this.head = head;
    }

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public Integer getLength() {
        return length;
    }

    public void setLength(Integer length) {
        this.length = length;
    }

    public Integer getCmd() {
        return cmd;
    }

    public void setCmd(Integer cmd) {
        this.cmd = cmd;
    }

    public Integer getSerial() {
        return serial;
    }

    public void setSerial(Integer serial) {
        this.serial = serial;
    }
}

定义消息体

/**
 * <p>
 * 消息内容
 * </p>
 *
 * @author : 钟满红
 */
public class MessageBody {
    /**
     * 存储数据
     */
    private String data;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

消息包

/**
 * <p>
 * 消息的实现
 * </p>
 *
 * @author : 钟满红
 */
public class NetMessage{
    private MessageHead messageHead;
    private MessageBody messageBody;

    public MessageHead getMessageHead() {
        return messageHead;
    }

    public void setMessageHead(MessageHead messageHead) {
        this.messageHead = messageHead;
    }

    public MessageBody getMessageBody() {
        return messageBody;
    }

    public void setMessageBody(MessageBody messageBody) {
        this.messageBody = messageBody;
    }

    public Integer getSerial(){
        return getNetMessageHead().getSerial();
    }

    public Integer getCmd(){
        return getNetMessageHead().getCmd();
    }

    public MessageHead getNetMessageHead() {
        return messageHead;
    }

    public MessageBody getNetMessageBody() {
        return messageBody;
    }
}

消息解码

/**
 * json转消息对象
 * @author : 钟满红
 */
public class JsonToMessageHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        ctx.fireChannelRead(JsonUtil.formJson(msg, NetMessage.class));
    }
}

消息分发

/**
 * 消息入口
 * @author : 钟满红
 */
public class NetMessageHandler extends SimpleChannelInboundHandler<NetMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, NetMessage msg) throws Exception {
        //todo 线程异步处理请求
    }
}

netty的channel初始化

/**
 * tcp
 *
 * @author : 钟满红
 */
public class TcpChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //半包解码器
        pipeline.addLast("lengthDecoder", new LengthFieldBasedFrameDecoder(1024 * 10, 0, 4, 0, 4));
        //半包编码器
        pipeline.addLast("lengthEncoder", new LengthFieldPrepender(4, false));
        //字符解码器
        pipeline.addLast("stringDecoder", new StringDecoder());
        //字符编码器
        pipeline.addLast("stringEncoder", new StringEncoder());
        //json转消息对象
        pipeline.addLast("jsonToMessage", new JsonToMessageHandler());
        //网络消息入口处理
        pipeline.addLast("messageHandler", new NetMessageHandler());

    }
}

netty服务组装

/**
 * 网络服务
 * @author : 钟满红
 */
public class NetService implements IService {

    private final NioEventLoopGroup boss = new NioEventLoopGroup(1);
    private final NioEventLoopGroup work = new NioEventLoopGroup();

    private ChannelFuture serverSocketFuture;
    @Override
    public void startup() throws Exception {
        int port = 8888;
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, work).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .option(ChannelOption.SO_BACKLOG, 500)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new TcpChannelInitializer());
        try {
            serverSocketFuture = bootstrap.bind(port).sync();
        } catch (Exception e) {
            shutdown();
        }
    }

    @Override
    public void shutdown() throws Exception {
        try {
            if (serverSocketFuture != null) {
                serverSocketFuture.channel().close().sync();
            }
        } catch (Exception e) {
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }
}

netty服务注入到Services

    /**
     * 网络服务
     */
    public static final NetService netService = valueOf(new NetService());

这篇关于java游戏服务器——Netty网络服务的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!