Netty客户端和服务端发送接收消息

效果图:服务端发送消息,客户端进行接收

 

说明:我们这个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.csdn.net/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);
   
  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值