前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >netty 3多客户端连接与心跳断开重连 顶

netty 3多客户端连接与心跳断开重连 顶

作者头像
算法之名
发布2019-08-20 11:04:41
1.7K0
发布2019-08-20 11:04:41
举报
文章被收录于专栏:算法之名算法之名

netty服务端

代码语言:javascript
复制
package com.netty.test3;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.handler.timeout.IdleStateHandler;
import org.jboss.netty.util.HashedWheelTimer;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2018-05-16.
 */
public class Server {
    public static void main(String[] args) {
        ServerBootstrap server = new ServerBootstrap();

        ExecutorService boss = Executors.newCachedThreadPool();
        ExecutorService worker = Executors.newCachedThreadPool();
        server.setFactory(new NioServerSocketChannelFactory(boss,worker));
        final HashedWheelTimer hashedWheelTimer = new HashedWheelTimer();
        server.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("idle",new IdleStateHandler(hashedWheelTimer,5,5,20));
                pipeline.addLast("decoder",new StringDecoder());
                pipeline.addLast("encoder",new StringEncoder());
                pipeline.addLast("hellohandler",new HelloHandler());
                return pipeline;
            }
        });
        server.bind(new InetSocketAddress(10101));
        System.out.println("Start!!!");
    }
}

netty服务端事件监听

代码语言:javascript
复制
package com.netty.test3;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.*;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;

/**
 * Created by Administrator on 2018-05-17.
 */
public class HelloHandler extends IdleStateAwareChannelHandler implements ChannelHandler {
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        System.out.println("messageReceived");
//        ChannelBuffer message = (ChannelBuffer)e.getMessage();
//        String s = new String(message.array());
        System.out.println((String)e.getMessage());
//        ChannelBuffer copiedBuffer = ChannelBuffers.copiedBuffer("欢迎光临".getBytes());
        ctx.getChannel().write("欢迎光临");
        super.messageReceived(ctx, e);
    }

    @Override
    public void channelIdle(final ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
        if ( e.getState() == IdleState.ALL_IDLE) {
            System.out.println("踢玩家下线");
            ChannelFuture write = ctx.getChannel().write("time out,you will close");
            write.addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    ctx.getChannel().close();
                }
            });
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        System.out.println("exceptionCaught");
        super.exceptionCaught(ctx, e);
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelConnected");
        super.channelConnected(ctx, e);
    }

    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelDisconnected");
        super.channelDisconnected(ctx, e);
    }

    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelClosed");
        super.channelClosed(ctx, e);
    }
}

netty多客户端代码

代码语言:javascript
复制
package com.netty.test3;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Administrator on 2018-05-21.
 */
public class MultClient {
    private ClientBootstrap client = new ClientBootstrap();
    private List<Channel> channels = new ArrayList<Channel>();
    private final AtomicInteger index = new AtomicInteger();
    public void init(int count) {
        ExecutorService boss = Executors.newCachedThreadPool();
        ExecutorService worker = Executors.newCachedThreadPool();
        client.setFactory(new NioClientSocketChannelFactory(boss,worker));
        client.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("decoder",new StringDecoder());
                pipeline.addLast("encoder",new StringEncoder());
                pipeline.addLast("hihandler",new HiHandler());
                return pipeline;
            }
        });
        for (int i = 1;i <= count;i++) {
            ChannelFuture future = client.connect(new InetSocketAddress("127.0.0.1", 10101));
            channels.add(future.getChannel());
        }
    }
    public Channel nextChannel() {
        return getFirstActiveChannel(0);
    }
    private Channel getFirstActiveChannel(int count) {
        Channel channel;
        if (count == 0) {
            channel = channels.get(0);
        }else {
            int tmpIndex = Math.abs(index.incrementAndGet() % channels.size());
            channel = channels.get(tmpIndex);
        }
        if (!channel.isOpen()) {
            reconnect(channel);
            if (count >= channels.size()) {
                throw new RuntimeException("no can use channel");
            }
            return getFirstActiveChannel(count + 1);
        }
        return channel;
    }
    private void reconnect(Channel channel) {
        synchronized (channel) {
            if (channels.indexOf(channel) == -1) {
                return;
            }
            Channel newChannel = client.connect(new InetSocketAddress("127.0.0.1",10101)).getChannel();
            channels.set(channels.indexOf(channel),newChannel);
        }
    }
}

客户端监听

代码语言:javascript
复制
package com.netty.test3;

import org.jboss.netty.channel.*;

/**
 * Created by Administrator on 2018-05-17.
 */
public class HiHandler extends SimpleChannelHandler {
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        System.out.println("messageReceived");
//        ChannelBuffer message = (ChannelBuffer)e.getMessage();
//        String s = new String(message.array());
        System.out.println((String)e.getMessage());
//        ChannelBuffer copiedBuffer = ChannelBuffers.copiedBuffer("fuck".getBytes());
//        ctx.getChannel().write("fuck");
        super.messageReceived(ctx, e);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        System.out.println("exceptionCaught");
        super.exceptionCaught(ctx, e);
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelConnected");
        super.channelConnected(ctx, e);
    }

    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelDisconnected");
        super.channelDisconnected(ctx, e);
    }

    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelClosed");
        super.channelClosed(ctx, e);
    }
}

客户端启动程序

代码语言:javascript
复制
package com.netty.test3;

import org.jboss.netty.channel.Channel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by Administrator on 2018-05-21.
 */
public class Start {
    public static void main(String[] args) {
        MultClient client = new MultClient();
        client.init(5);
        System.out.println("Client Start");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            try {
                System.out.println("请输入:");
                String msg = bufferedReader.readLine();
                Channel channel = client.nextChannel();
                if (channel.isConnected()) {
                    channel.write(msg);
                }else {
                    System.out.println("正在连接,请稍后...");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档