效果图:服务端发送消息,客户端进行接收
说明:我们这个netty需要用到jar包,请大家自行下载,添加
jar下载地址:http://netty.io/downloads.html
netty官方地址: http://netty.io/
netty4.x 官方地址:http://netty.io/wiki/user-guide-for-4.x.html
Netty 实现聊天功能:https://waylau.com/netty-chat/
netty实现长连接心跳检: https://blog.youkuaiyun.com/qq_19983129/article/details/53025732
1.服务端主方法main:
package comtest.example.admin.netty.server;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import comtest.example.admin.netty.client.NettyClientHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
/**
* Created by wrs on 2019/6/3,10:35
* projectName: Testz
* packageName: comtest.example.admin.netty.server
*/
public class NettyServer {
private int port = 20803;
//维护设备在线的表
private Map<String, Integer> clientMap = new HashMap<>();
public synchronized void setClient(String name) {
this.clientMap.put(name, 1);
}
public synchronized void removeClient(String name) {
this.clientMap.remove(name);
}
//判断连接处里面是否有东西
public synchronized boolean getClientMapSize() {
return this.clientMap.size() > 0;
}
//维护设备连接的map 用于推送消息
private Map<String, Channel> channelMap = new HashMap<>();
public synchronized void setChannel(String name, Channel channel) {
this.channelMap.put(name, channel);
}
public synchronized Map<String, Channel> getChannelMap() {
return this.channelMap;
}
//发送消息给下游设备
public boolean writeMsg(String msg) {
boolean errorFlag = false;
Map<String, Channel> channelMap = getChannelMap();
if (channelMap.size() == 0) {
return true;
}
Set<String> keySet = clientMap.keySet();
for (String key : keySet) {
try {
Channel channel = channelMap.get(key);