栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Netty服务端项目模块级代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Netty服务端项目模块级代码

文章目录
  • 前言
  • 一、初始化启动
  • 二、消息入站
  • 三、关于双方私定的协议
  • 另:请求体与响应体的包装
    • 请求体
    • 响应体
  • 四、消息处理器 - 策略模式
  • 另:关于消息码
  • 五、业务处理器
  • 六、消息的出站
  • 总结

前言

Netty服务端项目模块级代码

这一篇主要是用于使用 Socket 通信的端对端的项目,本篇采取Java代码编写服务端,通过自定义编解码器实现数据约定及安全性校对,如有BUG请广大网友批评指针。

下面展示项目的包结构:

  1. 最外层的类为Netty初始化及基础的通道处理;
  2. 其中有三个大目录,businesscodecprotocol,分别是业务包、编解码器、私定协议;
  3. request包及response包为请求消息体及响应消息体的封装;

将依赖引入后,将进行正式开始流程说明。


            io.netty
            netty-all
            4.1.68.Final
        

本文是采取与SpringBoot的结合方式进行编码。

一、初始化启动

首先将服务端进行进程启动。

NettyServerInitialize.java

package org.springblade.netty;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.CompletableFuture;


@Component
public class NettyServerInitialize {

	private static Logger log = LoggerFactory.getLogger(NettyServerInitialize.class);
	
	private static EventLoopGroup bossGroup;
	private static EventLoopGroup workerGroup;
	private static ServerBootstrap serverBootstrap;
	
	private static ChannelFuture channelFuture;
	
	private static Integer port = 10222;

	static {
		// Server初始化
		bossGroup = new NioEventLoopGroup(1);
		workerGroup = new NioEventLoopGroup(2);
		serverBootstrap =
			new ServerBootstrap().group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 128)
				.childOption(ChannelOption.SO_KEEPALIVE, true)
				.childHandler(new NettyServerChannel());
	}

	@PostConstruct
	public void starter() {
		CompletableFuture.runAsync(new Runnable() {
			@Override
			public void run() {
				try {
					channelFuture = serverBootstrap.bind(port)
						.addListener(new ChannelFutureListener() {
							@Override
							public void operationComplete(ChannelFuture future) throws Exception {
								if (future.isSuccess()) {
									System.out.println("监听端口 " + port + " 成功");
								} else {
									log.error("监听端口 " + port + " 失败");
								}
							}
						}).channel().closeFuture().sync();

				} catch (Exception e) {
					e.printStackTrace();
					bossGroup.shutdownGracefully();
					workerGroup.shutdownGracefully();
				}

			}
		});
	}
}

然后我们需要通道处理器进行流水线处理。

NettyServerChannel.java

package org.springblade.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import org.springblade.netty.codec.BusinessMsgDecoder;
import org.springblade.netty.codec.BusinessMsgEncoder;


public class NettyServerChannel extends ChannelInitializer {
	public NettyServerChannel() {
		super();
	}

	
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		super.handlerAdded(ctx);
	}

	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		super.exceptionCaught(ctx, cause);
	}

	
	@Override
	protected void initChannel(SocketChannel ch) {
		ChannelPipeline pipeline = ch.pipeline();
		// 编解码器 自定义
		pipeline.addLast(new BusinessMsgEncoder());
		pipeline.addLast(new BusinessMsgDecoder());
		pipeline.addLast(new NettyServerInboundHandler());
	}
}
二、消息入站

从上面的代码可以看到,我们在ChannelPipeline中加入了三个处理器,分别是

  1. 编码器;
  2. 解码器;
  3. 入站处理器;

我们按照数据的流入到转出纵观看向这幅代码,数据进站前,流入解码器。

BusinessMsgDecoder.java

package org.springblade.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.netty.protocol.MsgProtocol;
import org.springblade.netty.protocol.request.ServerRequest;
import org.springblade.netty.protocol.response.SendResponse;

import java.util.Arrays;
import java.util.List;


public class BusinessMsgDecoder extends ByteToMessageDecoder {

	private static final Logger logger = LoggerFactory.getLogger(BusinessMsgDecoder.class);

	
	@Override
	protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List list) throws Exception {
		// 数据包完整性校对
		Integer dateLength = MsgProtocol.flagSize + MsgProtocol.lengthSize + MsgProtocol.msgCodeSize;
		int readableBytes = byteBuf.readableBytes();
		if (byteBuf.readableBytes() < dateLength) {
			// 数据包长度不足
			logger.info("decode -- 数据包长度不足");
			return;
		}
		// 返回表示 ByteBuf 当前可读取的字节数
		byte[] req = new byte[readableBytes];
		// 把 ByteBuf 里面的数据全部读取到字节数组中
		byteBuf.readBytes(req);
		if (req[0] != 1) {
			logger.info("flag 错误");
			return;
		}
		// 参数体长度
		byte codeLength = req[4];
		if (codeLength != (req.length - 4 - 1)) {
			logger.info("数据包尚不完整");
			return;
		}
		// 协议码
		byte codeByte = req[8];
		if (readableBytes == 9) {
			// 无参传递
			list.add(new ServerRequest((int) codeByte, ""));
		} else {
			// 有参传递
			byte[] detailBytes = Arrays.copyOfRange(req, 11, req.length);
			list.add(new ServerRequest((int) codeByte, new String(detailBytes)));
		}
	}
}
 

当我们根据私定的协议对数据进行处理完成后,放入下一站处理器。

关于约定的协议格式后续会进行说明

NettyServerInboundHandler.java

package org.springblade.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.undertow.util.CopyOnWriteMap;
import org.springblade.netty.business.dispatcher.MsgDispatcher;
import org.springblade.netty.protocol.GameSession;
import org.springblade.netty.protocol.request.ServerRequest;
import org.springblade.netty.protocol.response.ResponseMsg;

import java.net.SocketAddress;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;


public class NettyServerInboundHandler extends ChannelInboundHandlerAdapter {

	
	private static CopyOnWriteMap mapChannel = new CopyOnWriteMap();

	
	private static MsgDispatcher msgDispatcher = new MsgDispatcher();

	
	public static void sendBroadcast(ResponseMsg msg) {
		Set setAddress = new HashSet<>();
		// 广播
		mapChannel.forEach(new BiConsumer() {
			@Override
			public void accept(String address, Channel channel) {
				if (channel.isActive()) {
					channel.writeAndFlush(msg);
				} else {
					setAddress.add(address);
				}
			}
		});
		// 将失活连接铲除
		for (String address : setAddress) {
			mapChannel.remove(address);
		}
	}

	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		mapChannel.remove(ctx.channel().remoteAddress().toString());
		super.channelInactive(ctx);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		SocketAddress remoteAddress = ctx.channel().remoteAddress();
		mapChannel.put(remoteAddress.toString(), ctx.channel());
		super.channelActive(ctx);
	}

	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ServerRequest serverRequest = (ServerRequest) msg;
		msgDispatcher.dispatchMsg(new GameSession(ctx), serverRequest);
	}

	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		super.channelReadComplete(ctx);
	}

	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
		cause.printStackTrace();
		super.exceptionCaught(ctx, cause);
	}
}
三、关于双方私定的协议

interface MsgProtocol

package org.springblade.netty.protocol;


public interface MsgProtocol {
	
	byte defaultFlag = 1;
	
	int maxPackLength = 1024 * 5;
	
	int flagSize = 1;
	
	int lengthSize = 4;
	
	int msgCodeSize = 4;
}
  • flag(1 byte)+length(4 byte,后边内容的长度)+protocol code(4 byte)+content
  • length的长度包括 :消息号 + 内容

另外对ChannelHandlerContext也有一层自己的包装GameSession

package org.springblade.netty.protocol;

import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import org.springblade.netty.protocol.response.ResponseMsg;


public class GameSession {

	
	private ChannelHandlerContext channelHandlerContext;

	
	public Boolean isOnline = false;

	
	public GameSession(ChannelHandlerContext channelHandlerContext) {
		this.channelHandlerContext = channelHandlerContext;
	}

	
	public void sendMessage(ResponseMsg msg){
		// ...校验是否登录
		// ...
		channelHandlerContext.writeAndFlush(msg);
	}
}
另:请求体与响应体的包装
  1. ServerRequest
  2. ResponseMsg
  3. ServerResponse
  4. SendResponse
  5. MsgBodyWrap
请求体
@Data
@AllArgsConstructor
public class ServerRequest {
	private Integer code;
	private String data;
}
响应体

ResponseMsg

package org.springblade.netty.protocol.response;


import io.netty.buffer.ByteBuf;


public interface ResponseMsg {

	
	public void setMsgCode(int code);

	
	public ByteBuf entireMsg(ByteBuf out);

	
	public void release();
}

public class ServerResponse implements ResponseMsg

package org.springblade.netty.protocol.response;


import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import org.springblade.netty.protocol.MsgProtocol;


public class ServerResponse implements ResponseMsg {
	protected MsgBodyWrap output = MsgBodyWrap.newInstance4Out();
	private int msgCode;
	private int status;

	
	public ServerResponse(int status, int msgCode) {
		setStatus(status);
		setMsgCode(msgCode);
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public void setMsgCode(int code) {
		msgCode = code;
	}

	public synchronized ByteBuf entireMsg(ByteBuf out) {
		byte[] body = output.toByteArray();
		// 标志 byte 长度short
		int length = MsgProtocol.flagSize+MsgProtocol.lengthSize+MsgProtocol.msgCodeSize+ body.length+4;
		// 处理
		out.writeByte(MsgProtocol.defaultFlag);
		out.writeInt(length);
		out.writeInt(msgCode);
		out.writeInt(status);
		out.writeBytes(body);
		return out;
	}

	
	public synchronized void release() {
		if (output != null) {
			output.close();
			output = null;
		}
		output = null;
	}
}

public class ServerResponse implements ResponseMsg

package org.springblade.netty.protocol.response;


import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import org.springblade.netty.protocol.MsgProtocol;


public class ServerResponse implements ResponseMsg {
	protected MsgBodyWrap output = MsgBodyWrap.newInstance4Out();
	private int msgCode;
	private int status;

	
	public ServerResponse(int status, int msgCode) {
		setStatus(status);
		setMsgCode(msgCode);
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public void setMsgCode(int code) {
		msgCode = code;
	}

	public synchronized ByteBuf entireMsg(ByteBuf out) {
		byte[] body = output.toByteArray();
		// 标志 byte 长度short
		int length = MsgProtocol.flagSize+MsgProtocol.lengthSize+MsgProtocol.msgCodeSize+ body.length+4;
		// 处理
		out.writeByte(MsgProtocol.defaultFlag);
		out.writeInt(length);
		out.writeInt(msgCode);
		out.writeInt(status);
		out.writeBytes(body);
		return out;
	}

	
	public synchronized void release() {
		if (output != null) {
			output.close();
			output = null;
		}
		output = null;
	}
}

public class SendResponse extends ServerResponse

package org.springblade.netty.protocol.response;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;


public class SendResponse extends ServerResponse {

	
	public SendResponse(int status, Object data, int msgCode, String detail) {
		super(status, msgCode);
		try {
			if (status > 0) {
				output.writeUTF(JSONObject.toJSONString(data));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			output.close();
		}
	}
}

最后就是这个消息体的封装

package org.springblade.netty.protocol.response;


import java.io.*;


public class MsgBodyWrap {
	private ByteArrayInputStream in;
	private ByteArrayOutputStream out;

	private DataInputStream dataIn;
	private DataOutputStream dataOut;

	public static MsgBodyWrap newInstance4In(byte[] buffer) {
		return new MsgBodyWrap(buffer);

	}

	public static MsgBodyWrap newInstance4Out() {
		return new MsgBodyWrap();
	}

	private MsgBodyWrap(byte[] buffer) {
		in = new ByteArrayInputStream(buffer);
		dataIn = new DataInputStream(in);
	}

	private MsgBodyWrap() {
		out = new ByteArrayOutputStream();
		dataOut = new DataOutputStream(out);
	}

	public byte readByte() throws IOException {
		return dataIn.readByte();
	}

	public int read() throws IOException {
		return dataIn.read();
	}

	public short readShort() throws IOException {
		return dataIn.readShort();
	}

	public int readInt() throws IOException {
		return dataIn.readInt();
	}

	public long readLong() throws IOException {
		return dataIn.readLong();
	}

	public float readFloat() throws IOException {
		return dataIn.readFloat();
	}

	public double readDouble() throws IOException {
		return dataIn.readDouble();
	}

	public String readUTF() throws IOException {
		return dataIn.readUTF();
	}

	public void writeByte(int value) throws IOException {
		dataOut.writeByte(value);
	}

	public void writeBoolean(boolean value) throws IOException {
		dataOut.writeBoolean(value);
	}

	public void writeBytes(byte[] value) throws IOException {
		dataOut.write(value);
	}

	public void writeShort(int value) throws IOException {
		dataOut.writeShort(value);
	}

	public void writeInt(int value) throws IOException {
		dataOut.writeInt(value);
	}

	public void writeLong(long value) throws IOException {
		dataOut.writeLong(value);
	}

	public void writeFloat(float value) throws IOException {
		dataOut.writeFloat(value);
	}

	public void writeDouble(double value) throws IOException {
		dataOut.writeDouble(value);
	}

	public void writeUTF(String value) throws IOException {
		int bufferSize = 2147483647;
		int i = 0;
		int sum = 0;
		while (i < value.length()) {
			int endIdx = java.lang.Math.min(value.length(), i + bufferSize);
			String jsosPart = value.substring(i, endIdx);
			dataOut.writeUTF(jsosPart);
			sum += jsosPart.length();
			i += bufferSize;
		}
		assert sum == value.length();
	}

	public byte[] toByteArray() {
		return this.out.toByteArray();
	}

	
	public void close() {
		if (in != null) {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (out != null) {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (dataIn != null) {
			try {
				dataIn.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (dataOut != null) {
			try {
				out.flush();
				dataOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
四、消息处理器 - 策略模式

通过上面说到,在入站消息完成解码工作后,开始对消息的消费,也就是我们的业务处理动作,此时我们需要区分消息,大量的if及switch显然并不优雅,所以这里是采取了策略模式。

MsgProcessor.java

package org.springblade.netty.business.dispatcher;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.netty.protocol.GameSession;
import org.springblade.netty.protocol.request.ServerRequest;


public abstract class MsgProcessor {

	private static final Logger logger = LoggerFactory.getLogger(MsgProcessor.class);

	public void handle(GameSession gameSession, ServerRequest serverRequest) {
		try {
			process(gameSession, serverRequest);
		} catch (Exception e) {
			logger.error("消息处理出错 - msg code:" + serverRequest.getCode());
			e.printStackTrace();
		}
	}

	public abstract void process(GameSession gameSession, ServerRequest serverRequest) throws Exception;
}

接下来是注册器与分配器,根据消息code进行区分.

分配器

package org.springblade.netty.business.dispatcher;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.netty.business.handle.INotAuthProcessor;
import org.springblade.netty.protocol.GameSession;
import org.springblade.netty.protocol.request.ServerRequest;

import java.util.HashMap;
import java.util.Map;



public class MsgDispatcher {

	private static final Logger logger = LoggerFactory.getLogger(MsgDispatcher.class);

	private Map processorsMap = new HashMap();

	public MsgDispatcher() {
		for (MsgProcessorRegister register : MsgProcessorRegister.values()) {
			processorsMap.put(register.getMsgCode(), register.getProcessor());
		}
		logger.info("初始化 消息处理器成功 --- ");
	}

	
	public MsgProcessor getMsgProcessor(int msgCode) {
		return processorsMap.get(msgCode);
	}

	
	public void dispatchMsg(GameSession gameSession, ServerRequest serverRequest) {
		MsgProcessor processor = getMsgProcessor(serverRequest.getCode());
		// 是否登录判断
		try {
			if (true || processor instanceof INotAuthProcessor) {
				processor.handle(gameSession, serverRequest);
			}
		} catch (NullPointerException e) {
			logger.error("存在未实现的接口:接口码 = " + serverRequest.getCode());
			e.printStackTrace();
		}

	}
}

注册器

package org.springblade.netty.business.dispatcher;

import lombok.Getter;
import org.springblade.netty.business.MsgCode;
import org.springblade.netty.business.handle.LoginMsgHandler;


@Getter
public enum MsgProcessorRegister {

	
	login(MsgCode.CODE_1.getReq(), new LoginMsgHandler()),
	;

	private int msgCode;
	private MsgProcessor processor;

	
	private MsgProcessorRegister(int msgCode, MsgProcessor processor) {
		this.msgCode = msgCode;
		this.processor = processor;
	}
}
另:关于消息码
package org.springblade.netty.business;

import lombok.Getter;


@Getter
public enum MsgCode {

	// 系统级请求响应从 1 开始 
	
	CODE_1(1, 2),

	// 业务级请求响应从 100 开始 //
	
	CODE_100(101, 102),

	/ 广播消息从 300 开始 
	
	CODE_301(0, 301);


	
	private Integer req;
	
	private Integer resp;

	MsgCode(Integer req_code, Integer resp_code) {
		this.req = req_code;
		this.resp = resp_code;
	}
}
五、业务处理器

此时的业务处理器,需要实现上述的MsgProcessor,通过多态实现设计模式中的策略模式。

package org.springblade.netty.business.handle;

import org.springblade.core.tool.api.R;
import org.springblade.netty.business.MsgCode;
import org.springblade.netty.business.dispatcher.MsgProcessor;
import org.springblade.netty.protocol.GameSession;
import org.springblade.netty.protocol.request.ServerRequest;
import org.springblade.netty.protocol.response.SendResponse;

import java.util.HashMap;
import java.util.Map;

public class LoginMsgHandler extends MsgProcessor implements INotAuthProcessor {
	@Override
	public void process(GameSession gameSession, ServerRequest serverRequest) throws Exception {

		// ...业务处理
		Map map = new HashMap<>();

		map.put("realName", "牛逼");
		map.put("faceInformation", "");
		map.put("isLogin", true);
		map.put("msg", 1);//成功
		map.put("user", null);

		// ...
		R loginInfo = R.data(map);

		// 返回数据
		// ...0x000002
		gameSession.sendMessage(new SendResponse(200, loginInfo, MsgCode.CODE_1.getResp(), "测试我登录成功了"));

	}
}

然而我们也需要有无需校验的接口标识

package org.springblade.netty.business.handle;


public interface INotAuthProcessor {
}
六、消息的出站

完成业务代码后,将消息发送到对端的客户端,此时需要编码器的处理。

package org.springblade.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.springblade.netty.protocol.response.ResponseMsg;


public class BusinessMsgEncoder extends MessageToByteEncoder {
	@Override
	protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
		// 引用计数处理 - 多出站处理器会导致资源过度释放
		out.retain();
		ResponseMsg valueMsg = (ResponseMsg) msg;
		ctx.writeAndFlush(valueMsg.entireMsg(out));
		// 资源释放
		valueMsg.release();
	}
}
总结

我的工作中作为服务器开发经常要与各式各样的客户端进行对接,在本次的项目中,将apache mina框架完美平移到了Netty中,花了两天的时间,也算是收获颇多。

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号