分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.youkuaiyun.com/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
通过netty实现服务端与客户端的长连接通讯,及心跳检测。
基本思路:netty服务端通过一个Map保存所有连接上来的客户端SocketChannel,客户端的Id作为Map的key。每次服务器端如果要向某个客户端发送消息,只需根据ClientId取出对应的SocketChannel,往里面写入message即可。心跳检测通过IdleEvent事件,定时向服务端放送Ping消息,检测SocketChannel是否终断。
环境JDK1.8 和netty5
以下是具体的代码实现和介绍:
1公共的Share部分(主要包含消息协议类型的定义)
设计消息类型:
public enum MsgType { PING,ASK,REPLY,LOGIN}
Message基类:
//必须实现序列,serialVersionUID 一定要有,否者在netty消息序列化反序列化会有问题,接收不到消息!!!public abstract class BaseMsg implements Serializable { private static final long serialVersionUID = 1L; private MsgType type; //必须唯一,否者会出现channel调用混乱 private String clientId; //初始化客户端id public BaseMsg() { this.clientId = Constants.getClientId(); } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public MsgType getType() { return type; } public void setType(MsgType type) { this.type = type; }}
常量设置:
public class Constants { private static String clientId; public static String getClientId() { return clientId; } public static void setClientId(String clientId) { Constants.clientId = clientId; }}
登录类型消息:
public class LoginMsg extends BaseMsg { private String userName; private String password; public LoginMsg() { super(); setType(MsgType.LOGIN); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
心跳检测Ping类型消息:
public class PingMsg extends BaseMsg { public PingMsg() { super(); setType(MsgType.PING); }}
请求类型消息:
public class AskMsg extends BaseMsg { public AskMsg() { super(); setType(MsgType.ASK); } private AskParams params; public AskParams getParams() { return params; } public void setParams(AskParams params) { this.params = params; }}//请求类型参数//必须实现序列化接口public class AskParams implements Serializable { private static final long serialVersionUID = 1L; private String auth; public String getAuth() { return auth; } public void setAuth(String auth) { this.auth = auth; }}
响应类型消息:
public class ReplyMsg extends BaseMsg { public ReplyMsg() { super(); setType(MsgType.REPLY); } private ReplyBody body; public ReplyBody getBody() { return body; } public void setBody(ReplyBody body) { &nb