基于netty实现群聊系统

这里不再详细介绍netty是什么,可以网上查资料学习
直接开干~~~~

1、创建服务器
package nettypro.netty.groupchat;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @ClassName GroupChatServer
 * @Description netty服务器
 * @Author zeny
 * @Date 2020/3/24 0024 21:13
 */
public class GroupChatServer {
    private int port;
    private GroupChatServer(int port) {
        this.port = port;
    }

	/**
	ChannelOption.SO_BACKLOG, 128 : 对应 TCP/IP 协议 listen 函数中的 backlog 参数,用来初始化服务器可连接队列大小。服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接。多个客户端来的时候,服务端将不能处理的客户端连接请求放在队列中等待处理,backlog 参数指定了队列的大小;
	ChannelOption.SO_KEEPALIVE, true: 一直保持连接活动状态
	 */
    public void run(){
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup(8);
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //加入解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            //加入编码器
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast(new GroupChatServerHandler());
                        }
                    });
            System.out.println("netty server is starting......");
            ChannelFuture channelFuture = bootstrap.bind(this.port).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e) {

        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }
    public static void main(String[] args){
        new GroupChatServer(8888).run();
    }
}

2、创建服务端handler
package nettypro.netty.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.aspectj.apache.bcel.generic.NEW;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName GroupChatServerHandler
 * @Description 具体处理
 * @Author zeny
 * @Date 2020/3/24 0024 21:26
 */
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    //定义一个channel组,管理所有的channel,GlobalEventExecutor.INSTANCE 是全局事件执行器,单例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * @Description 连接时首先执行,保存每个channel,并给所有channel提示
     * @Date 2020/3/24 0024 21:32
     * @param ctx
     * @return void
     **/
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //给每个channel发送消息
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + "在 " + simpleDateFormat.format(new Date()) + " 加入聊天\n");
        channelGroup.add(channel);
    }

    /**
     * @Description channel处于活动状态,提示xxx上线
     * @Date 2020/3/24 0024 21:38
     * @param ctx
     * @return void
     **/
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "上线了......");
    }

    /**
     * @Description channel离线
     * @Date 2020/3/24 0024 21:40
     * @param ctx
     * @return void
     **/
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "离线了......");
    }

    /**
     * @Description 断开连接,并提示给在线用户
     * @Date 2020/3/24 0024 21:41
     * @param ctx
     * @return void
     **/
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //自动移除当前channel
        channelGroup.writeAndFlush("[客户端]" + ctx.channel().remoteAddress() + " 离开了......\n");
    }

    /**
     * @Description 处理数据
     * @Date 2020/3/24 0024 21:43
     * @param ctx
     * @param msg
     * @return void
     **/
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach(ch -> {
            if (ch != channel) {
                //不是当前channel,转发
                ch.writeAndFlush("[客户]" + channel.remoteAddress() + " 说: " + msg + "\n");
            }else {
                ch.writeAndFlush("[自己] 说: " + msg + "\n");
            }
        });
    }

    /**
     * @Description 处理异常
     * @Date 2020/3/24 0024 21:48
     * @param ctx
     * @param cause
     * @return void
     **/
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}

这个handler添加在pipeline里面

在这里插入图片描述
至此,服务端已经写好了~~~

3、编写客户端
package nettypro.netty.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @ClassName GroupChatClient
 * @Description 客户端
 * @Author zeny
 * @Date 2020/3/24 0024 21:53
 */
public class GroupChatClient {
    private final String host;
    private final int port;

    public GroupChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast(new GroupChatClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(this.host, this.port).sync();
            Channel channel = channelFuture.channel();
            System.out.println("--------" + channel.localAddress() + "--------");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
            	//发送内容
                String msg = scanner.nextLine();
                channel.writeAndFlush(msg + "\r\n");
            }

        }catch (Exception e) {

        }finally {
            group.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        new GroupChatClient("127.0.0.1", 8888).run();
    }
}

4、编写handler显示服务器回送过来的数据
package nettypro.netty.groupchat;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @ClassName GroupChatClientHandler
 * @Description TODO
 * @Author zeny
 * @Date 2020/3/24 0024 22:06
 */
public class GroupChatClientHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    	//服务器发过来的内容
        System.out.println(msg.trim());
    }
}

5、效果

服务器:
在这里插入图片描述
客户端:
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要基于 Netty 实现一个 SOCKS5 服务器,可以按照以下步骤进行: 1. 创建一个 Netty 的 ServerBootstrap 对象,并设置其相关属性,例如监听端口号、处理器等。 2. 在处理器中实现 SOCKS5 协议的解析和处理。对于 SOCKS5 协议,客户端会发送一个 Greeting 消息,服务器需要回复一个 Greeting 消息确认连接。然后客户端会发送一个请求,包括请求类型、目标地址和端口等信息,服务器需要根据请求类型进行相应的处理,例如连接目标地址和端口、绑定到指定的地址和端口等。 3. 在处理器中实现数据的转发,当客户端和目标服务器建立连接后,服务器需要将数据从客户端转发给目标服务器,然后将目标服务器返回的数据转发给客户端。 下面是一个简单的示例代码: ```java public class Socks5Server { public static void main(String[] args) throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new Socks5ServerEncoder()); pipeline.addLast(new Socks5InitialRequestDecoder()); pipeline.addLast(new Socks5ServerHandler()); } }); ChannelFuture future = bootstrap.bind(1080).sync(); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } ``` 在上面的代码中,创建了一个 ServerBootstrap 对象,并设置了监听端口号为 1080,处理器为 Socks5ServerHandler。Socks5ServerHandler 实现了 SOCKS5 协议的解析和处理,以及数据的转发。 需要注意的是,这只是一个简单的示例代码,实际使用中可能需要根据具体需求进行扩展和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值