java游戏服务器开发之七--使用IServer控制服务的启动与关闭

 之前我们启动服务器都是直接这么写的
Channel acceptorChannel = ServerChannelFactory.createAcceptorChannel()
acceptorChannel.closeFuture().sync()
 这样子也没办法关闭,我们就可以想到用一个专门的类进行管理  IServer
 这个类主要三个方法,start/stop/restart
 使用接口的方式,让具体的类实现它,后面扩展也会方便点

 实现类BasicServerImpl通过@Component注解,交由spring管理

看下具体写法

IServer

/**
 * Copyright (C), 2015-2018
 * FileName: IServer
 * Author:   zhao
 * Date:     2018/6/20 20:20
 * Description: Server服务核心
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.lizhaoblog.base.network;

/**
 * 〈一句话功能简述〉<br> 
 * 〈Server服务核心〉
 *
 * @author zhao
 * @date 2018/6/20 20:20
 * @since 1.0.0
 */
public interface IServer {
  /**
   * 服务启动
   * @throws Exception
   */
  void start() throws Exception;

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

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

BasicServerImpl

/**
 * Copyright (C), 2015-2018
 * FileName: BasicServerImpl
 * Author:   zhao
 * Date:     2018/6/20 20:23
 * Description: BasicServerImpl
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.lizhaoblog.server.core;

import com.lizhaoblog.base.factory.ServerChannelFactory;
import com.lizhaoblog.base.network.IServer;

import org.springframework.stereotype.Component;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;

/**
 * 〈一句话功能简述〉<br>
 * 〈BasicServerImpl〉
 *
 * @author zhao
 * @date 2018/6/20 20:23
 * @since 1.0.0
 */
@Component
public class BasicServerImpl 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();
  }
}
然后我们在main函数里面的方法就可以改成
    IServer server = (IServer)ServerConfig.getInstance().getApplicationContext().getBean("basicServerImpl");

    server.start();


这样服务也可以启动成功了


上面的代码在码云上 https://gitee.com/lizhaoandroid/JgServer
可以加qq群一起探讨Java游戏服务器开发的相关知识 676231524

猜你喜欢

转载自blog.csdn.net/cmqwan/article/details/80752576
今日推荐