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);
   
好的,下面是一个简单的 Netty 客户服务示例代码,可以相互发送消息服务代码: ```java public class NettyServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 接收客户消息 ByteBuf buf = (ByteBuf) msg; String request = buf.toString(CharsetUtil.UTF_8); System.out.println("Client request: " + request); // 向客户发送响应消息 String response = "Hello, Client!"; ByteBuf respBuf = Unpooled.copiedBuffer(response, CharsetUtil.UTF_8); ctx.writeAndFlush(respBuf); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 发生异常时关闭连接 cause.printStackTrace(); ctx.close(); } } ``` 客户代码: ```java public class NettyClientHandler extends ChannelOutboundHandlerAdapter { private ChannelHandlerContext ctx; @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { // 向服务发送消息 ByteBuf buf = Unpooled.copiedBuffer(msg.toString(), CharsetUtil.UTF_8); ctx.writeAndFlush(buf); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 接收服务的响应 ByteBuf buf = (ByteBuf) msg; String response = buf.toString(CharsetUtil.UTF_8); System.out.println("Server response: " + response); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 发生异常时关闭连接 cause.printStackTrace(); ctx.close(); } } ``` 启动代码: ```java public class NettyDemo { public static void main(String[] args) throws InterruptedException { // 创建 EventLoopGroup EventLoopGroup group = new NioEventLoopGroup(); try { // 创建 ServerBootstrap ServerBootstrap serverBootstrap = new ServerBootstrap(); // 配置 ServerBootstrap serverBootstrap.group(group) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(8888)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyServerHandler()); } }); // 启动服务 ChannelFuture serverFuture = serverBootstrap.bind().sync(); // 创建 Bootstrap Bootstrap clientBootstrap = new Bootstrap(); // 配置 Bootstrap clientBootstrap.group(group) .channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress("localhost", 8888)) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyClientHandler()); } }); // 启动客户 ChannelFuture clientFuture = clientBootstrap.connect().sync(); // 客户服务发送消息 NettyClientHandler clientHandler = (NettyClientHandler) clientFuture.channel().pipeline().last(); clientHandler.write("Hello, Server!"); // 关闭客户服务 clientFuture.channel().closeFuture().sync(); serverFuture.channel().closeFuture().sync(); } finally { // 释放资源 group.shutdownGracefully().sync(); } } } ``` 在上面的代码中,服务使用 `ChannelInboundHandlerAdapter` 处理客户的请求,客户使用 `ChannelOutboundHandlerAdapter` 向服务发送请求。在启动代码中,先启动服务,再启动客户,并使用 `ChannelFuture` 对象获取客户的 `NettyClientHandler` 对象,通过该对象向服务发送消息。需要注意的是,客户服务都需要使用同一个 `EventLoopGroup`。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值