Netty搭建tcp服务器与websocket服务器示例

 搭建tcp服务器:

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * User: linxz
 * Date: 2019-12-04 16:10
 **/
public class NettyServer{
    
    public NettyServer(int port){
        NioEventLoopGroup boosGroup = null;
        NioEventLoopGroup workGroup = null;
        try {
            System.out.println("开始创建netty TCP服务");
            boosGroup=new NioEventLoopGroup();
            workGroup=new NioEventLoopGroup();
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup,workGroup);
            //系统用于临时存放已完成三次握手的请求的队列的最大长度,如果连接建立频繁,服务器处理创建新连接较慢,可以适当调大这个参数
            serverBootstrap.option(ChannelOption.SO_BACKLOG,1024);
            serverBootstrap.channel(NioServerSocketChannel.class);
            //一定要用这种方式设置handler,否则客户端一旦关闭连接之后就连接不上来
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new MsgHandler());
                }
            });
            Channel serverChannel = serverBootstrap.bind(port).sync().channel();
            System.out.println("netty TCP服务启动成功,端口:" + port);
            serverChannel.closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(workGroup!=null){
                workGroup.shutdownGracefully();
            }
            if(boosGroup!=null){
                boosGroup.shutdownGracefully();
            }
            System.out.println("程序异常结束");
        }
    }

    class MsgHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            Channel channel=ctx.channel();
            InetSocketAddress address = (InetSocketAddress)channel.remoteAddress();
            String ip=address.getAddress().getHostAddress();
            int port=address.getPort();
            System.out.println("有client加入-"+ip+":"+port);
        }

        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            Channel channel=ctx.channel();
            InetSocketAddress address = (InetSocketAddress)channel.remoteAddress();
            String ip=address.getAddress().getHostAddress();
            int port=address.getPort();
            System.out.println("有client断开连接-"+ip+":"+port);
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("接收到了数据");
            System.out.println("接收到的数据对象类型:"+msg.getClass());
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);//.addListener(ChannelFutureListener.CLOSE);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("触发exceptionCaught");
            cause.printStackTrace();
            ctx.close();
        }
    }
}

搭建websocket服务器:

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.ImmediateEventExecutor;

import java.net.InetSocketAddress;

/**
 * User: linxz
 * Date: 2019-12-04 16:14
 **/
public class WebSocketServer {

    //所有的websocket连接
    private static final ChannelGroup channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);

    /**
     * 给客户端发送消息
     */
    public static final void sendMsg(String msg){
        if(channelGroup.isEmpty()){
            System.out.println("暂无客户端连接!");
            return ;
        }
        channelGroup.writeAndFlush(new TextWebSocketFrame(msg));
    }

    public WebSocketServer(int port){
        NioEventLoopGroup boosGroup = null;
        NioEventLoopGroup workGroup = null;
        try {
            System.out.println("开始创建netty websocket服务");
            boosGroup=new NioEventLoopGroup();
            workGroup=new NioEventLoopGroup();
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup,workGroup);
            //系统用于临时存放已完成三次握手的请求的队列的最大长度,如果连接建立频繁,服务器处理创建新连接较慢,可以适当调大这个参数
            serverBootstrap.option(ChannelOption.SO_BACKLOG,1024);
            serverBootstrap.channel(NioServerSocketChannel.class);
            //一定要用这种方式设置handler,否则客户端一旦关闭连接之后就连接不上来
            serverBootstrap.childHandler(new SocketChannelInitializer(channelGroup));
            Channel serverChannel = serverBootstrap.bind(port).sync().channel();
            System.out.println("netty websocket服务启动成功,端口:" + port);
            serverChannel.closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(workGroup!=null){
                workGroup.shutdownGracefully();
            }
            if(boosGroup!=null){
                boosGroup.shutdownGracefully();
            }
            System.out.println("程序异常结束");
        }
    }
}

class SocketChannelInitializer extends ChannelInitializer<Channel> {

    private final ChannelGroup group;

    public SocketChannelInitializer(ChannelGroup group){
        this.group=group;
    }

    @Override
    protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(new WebSocketHandler(group));
    }
}

class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private final ChannelGroup group;

    public WebSocketHandler(ChannelGroup group) {
        this.group=group;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel=ctx.channel();
        InetSocketAddress address = (InetSocketAddress)channel.remoteAddress();
        String ip=address.getAddress().getHostAddress();
        int port=address.getPort();
        System.out.println("有连接加入,"+ip+":"+port);
        group.add(channel);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) throws Exception {
        System.out.println("收到客户端发送的消息:"+msg.text());
    }



    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel=ctx.channel();
        InetSocketAddress address = (InetSocketAddress)channel.remoteAddress();
        String ip=address.getAddress().getHostAddress();
        int port=address.getPort();
        System.out.println("有连接断开,"+ip+":"+port);
        group.remove(channel);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("websocket处理错误。");
        cause.printStackTrace();
        super.exceptionCaught(ctx, cause);
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值