从零开始手写mmo游戏从框架到爆炸(三)— 服务启动接口与网络事件监听器

上一章我们完成了netty服务启动的相关抽象(https://blog.csdn.net/money9sun/article/details/136025471),这一章我们再新增一个全局的服务启动类,方便后续扩展。

服务启动

新增的两个类如下:

定义一个接口IServer

java 复制代码
public interface IServer {

    /**
     * 服务启动
     * @throws Exception
     */
    void start() throws Exception;

    /**
     * 服务关闭
     * @throws Exception
     */
    void stop() throws Exception;

    /**
     * 服务重启
     * @throws Exception
     */
    void restart() throws Exception;

}

定义实现类 BasicServer

java 复制代码
import com.loveprogrammer.base.factory.ServerChannelFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;

/**
 * @ClassName BasicServer
 * @Description  网络服务启动实现
 * @Author admin
 * @Date 2024/2/4 16:25
 * @Version 1.0
 */
public class BasicServer implements IServer{
    Channel acceptorChannel;

    @Override
    public void start() throws Exception {
        acceptorChannel = ServerChannelFactory.createAcceptorChannel();
        acceptorChannel.closeFuture().sync();
    }
    @Override
    public void stop() throws Exception {
        if(acceptorChannel != null) {
            acceptorChannel.close().addListener(ChannelFutureListener.CLOSE);
        }
    }
    @Override
    public void restart() throws Exception {
        stop();
        start();
    }
}

启动类修改:

java 复制代码
        
        // 启动类启动
        try {
            IServer server = new BasicServer();
            server.start();
        } catch (Exception e) {
            LOGGER.error( "服务器启动失败",e);
        }

网络事件监听器

创建一个类,用于监听网络的变化,创建一个接口INetworkEventListener,里面包含3个方法,onConnected/onDisconnected/onExceptionCaught。依然创建在core组件中

java 复制代码
public interface INetworkEventListener {

    /**
     * 连接建立
     *
     * @param ctx ChannelHandlerContext
     */
    void onConnected(ChannelHandlerContext ctx);

    /**
     * 连接断开
     * * @param ctx ChannelHandlerContext
     */
    void onDisconnected(ChannelHandlerContext ctx);

    /**
     * 异常发生
     * * @param ctx ChannelHandlerContext
     * * @param throwable 异常
     */
    void onExceptionCaught(ChannelHandlerContext ctx, Throwable throwable);

}

监听器实现类 NetworkListener:

复制代码
package com.loveprogrammer.base.network.support;

import com.loveprogrammer.base.network.listener.INetworkEventListener;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NetworkListener implements INetworkEventListener {

    protected static final Logger logger = LoggerFactory.getLogger(NetworkListener.class);

    @Override
    public void onConnected(ChannelHandlerContext ctx) {
        logger.info("建立连接");
    }

    @Override
    public void onDisconnected(ChannelHandlerContext ctx) {
        logger.info("建立断开");
    }

    @Override
    public void onExceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
        logger.warn("异常发生", throwable);
    }
}

然后我们要修改TcpServerStringInitializer

java 复制代码
public class TcpServerStringInitializer  extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("framer",new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        INetworkEventListener listener = new NetworkListener();
        pipeline.addLast(new TcpMessageStringHandler(listener));
    }

}

TcpMessageStringHandler.java 修改如下

java 复制代码
package com.loveprogrammer.base.network.channel.tcp.str;

import com.loveprogrammer.base.network.listener.INetworkEventListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName TcpMessageStringHandler
 * @Description tcp消息处理类
 * @Author admin
 * @Date 2024/2/4 15:16
 * @Version 1.0
 */
public class TcpMessageStringHandler extends SimpleChannelInboundHandler<String> {
    private static final Logger logger = LoggerFactory.getLogger(TcpMessageStringHandler.class);

    private final INetworkEventListener listener;

    public TcpMessageStringHandler(INetworkEventListener listener) {
        this.listener = listener;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
        listener.onExceptionCaught(ctx,throwable);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        logger.info("数据内容:data=" + msg);
        String result = "我是服务器,我收到了你的信息:" + msg;
        result += "\r\n";
        ctx.writeAndFlush(result);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        listener.onConnected(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        listener.onDisconnected(ctx);
    }
}

上一章:

从零开始手写mmo游戏从框架到爆炸(二)--- 核心组件抽离与工厂模式创建-CSDN博客

下一章:

从零开始手写mmo游戏从框架到爆炸(四)--- session session-CSDN博客

全部源码详见:

gitee : eternity-online: 多人在线mmo游戏 - Gitee.com

分支:step-03

参考:

java游戏服务器开发: https://blog.csdn.net/cmqwan/category_7690685.html

相关推荐
豆沙沙包?10 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
程序员大辉16 小时前
游戏常用运行库合集 | GRLPackage 游戏运行库!
游戏
不伤欣19 小时前
游戏设计模式 - 子类沙箱
游戏·unity·设计模式
阿阳微客1 天前
Steam 搬砖项目深度拆解:从抵触到真香的转型之路
前端·笔记·学习·游戏
m0_552200822 天前
《UE5_C++多人TPS完整教程》学习笔记37 ——《P38 变量复制(Variable Replication)》
c++·游戏·ue5
量子炒饭大师4 天前
项目实战——C语言扫雷游戏
c语言·开发语言·游戏
开开心心就好4 天前
高效视频倍速播放插件推荐
python·学习·游戏·pdf·计算机外设·电脑·音视频
DanmF--4 天前
C#面向对象实践项目--贪吃蛇
开发语言·游戏·c#·游戏程序
Code_流苏5 天前
Python趣学篇:从零打造智能AI井字棋游戏(Python + Tkinter + Minimax算法)
python·算法·游戏·tkinter·智能井字棋·minimax算法
RedJACK~5 天前
【Go语言】Ebiten游戏库开发者文档 (v2.8.8)
开发语言·游戏·golang