java Netty应用实例-群聊系统

一、实例要求:

1)编写一个Netty群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)

2)实现多人群聊

3)服务器端:可以监测用户上线,离线,并实现消息转发功能。

4)客户端:通过channel可以无阻塞发送消息给其他所有用户,同时可以接受其他用户发送的消息(有服务器转发得到)

5)目的:进一步理解Netty非阻塞网络编程机制。

二、以下为实现代码

1.服务器端GroupChatServer.java

package com.tfq.netty.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;

/**
 * @author: fqtang
 * @date: 2024/04/03/13:39
 * @description: 描述
 */
public class GroupChatServer {
	//监听端口
	private int port;

	public GroupChatServer(int port) {
		this.port = port;
	}

	/**
	 * 处理客户端的请求
	 */
	public void run() throws InterruptedException {

		//创建两个线程组
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup(8);
		try {

			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(bossGroup, workerGroup)
				.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 {
						//获取到pipeline
						ChannelPipeline pipeline = ch.pipeline();
						//向pipeline加入一个解码器
						pipeline.addLast("decoder", new StringDecoder());
						//向pipeline加入一个编码器
						pipeline.addLast("encoder", new StringEncoder());
						//加入自己的业务处理handler
						pipeline.addLast(new GroupChatServerHandler());
					}
				});

			System.out.println("netty 服务器启动");
			ChannelFuture channelFuture = serverBootstrap.bind(port)
				.sync();
			channelFuture.channel()
				.closeFuture()
				.sync();
		}finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) {
		try {
			new GroupChatServer(7888).run();
		} catch(InterruptedException e) {
			throw new RuntimeException(e);
		}
	}

}

服务器端的handler处理:

package com.tfq.netty.netty.groupchat;

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

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;

/**
 * @author: fqtang
 * @date: 2024/04/03/13:53
 * @description: 描述
 */
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

	/**
	 * 定义一个channel组,管理所有的channel
	 * GlobalEventExecutor.INSTANCE是全局的事件执行器,是一个单例
	 */
	private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * 表示连接建立,一旦连接,第一个被执行
	 * 将当前channel加入到 channelGroup
	 *
	 * @param ctx
	 * @throws Exception
	 */
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		//将该客户加入聊天的信息推送给其他在线的客户端
		//该方法会将channelGroup 中所有的channel 遍历,并发送消息,我们不需要自己遍历
		channels.writeAndFlush(sdf.format(new Date())+" [客户端]" + channel.remoteAddress() + " 加入聊天\n");
		channels.add(channel);
	}

	/**
	 * 表示channel 处于活动上线,提示 xx上线
	 *
	 * @param ctx
	 * @throws Exception
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel()
			.remoteAddress() + " 在[ "+sdf.format(new Date())+" ] 上线了~");
	}

	/**
	 * 表示channel 处于离线,提示 xx离线
	 *
	 * @param ctx
	 * @throws Exception
	 */
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel()
			.remoteAddress() + "在 "+sdf.format(new Date())+" 离线了~");
	}

	/**
	 * 断开连接,将XX客户离开信息推送给当前在线的客户
	 *
	 * @param ctx
	 * @throws Exception
	 */
	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		channels.writeAndFlush("[客户端]" + channel.remoteAddress() + "在 【"+ sdf.format(new Date()) +"】 离开\n");
		System.out.println("移除通道"+channel.hashCode()+",当前通道总数:" + channels.size());
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		//获取当前通道channel
		Channel channel = ctx.channel();
		//这时我们遍历channels,根据不同的情况,返回不同的不同消息
		channels.forEach(c -> {
			if(channel !=c){//不是当前的channel,直接打印消息
				//把当前通道的消息转发给其他通道了
				c.writeAndFlush("[客户]" + channel.remoteAddress()+ "在 【"+ sdf.format(new Date()) + "】 发送了消息:"+ msg +" \n");
			}else {
				c.writeAndFlush("【自己】在 【"+ sdf.format(new Date()) +"】 发送了消息"+msg+"\n");
			}
		});
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		//关闭通道
		ctx.close();
		System.out.println("在 【"+sdf.format(new Date()) +"】 关闭通道,通道总数:" + channels.size());
	}
}

2.客户端GroupChatClient.java

package com.tfq.netty.netty.groupchat;

import java.util.Scanner;

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;


/**
 * @author: fqtang
 * @date: 2024/04/04/7:54
 * @description: 描述
 */
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 eventLoopGroup = new NioEventLoopGroup();

		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(eventLoopGroup)
				.channel(NioSocketChannel.class)
				.handler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						//得到pipeline
						ChannelPipeline pipeline = ch.pipeline();
						//加入相关handler的解码器
						pipeline.addLast("decoder", new StringDecoder());
						//加入相关handler的编码器
						pipeline.addLast("encoder", new StringEncoder());
						//加入自定义的handler
						pipeline.addLast(new GroupChatClientHandler());
					}
				});
			//连接服务器返回通道
			ChannelFuture channelFuture = bootstrap.connect(host, port)
				.sync();
			Channel channel = channelFuture.channel();

			if(channelFuture.isSuccess()) {
				System.out.println("本地ip:"+channel.localAddress()+",连接服务器ip: "+channel.remoteAddress() + " 成功");
			}

			Scanner scanner = new Scanner(System.in);
			while(scanner.hasNextLine()) {
				channel.writeAndFlush(scanner.nextLine());
			}

			//给关闭监听进行通道
			channel.closeFuture()
				.sync();

		} catch(InterruptedException e) {
			throw new RuntimeException(e);
		} finally {
			eventLoopGroup.shutdownGracefully();
		}

	}

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

客户端的handler处理

package com.tfq.netty.netty.groupchat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author: fqtang
 * @date: 2024/04/04/8:16
 * @description: 描述
 */
public class GroupChatClientHandler extends SimpleChannelInboundHandler<String> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		System.out.println(msg.trim());
	}
}

先运行GroupChatServer.java,然后运行多个GroupChatClient客户端。若用Idea开发则设置运行多个 客户。如下图:

运行如下图所示:

完毕。

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Netty-WebSocket-Spring-Boot-Starter是一个用于将Websocket集成到Spring Boot应用程序中的库。它使用Netty作为底层框架,提供了一种快速和可靠的方式来处理异步通信。 这个库提供了一种简单的方法来创建Websocket端点,只需要使用注释和POJO类即可。在这些端点上可以添加动态的事件处理程序,以处理连接、断开连接和消息事件等。 此外,Netty-WebSocket-Spring-Boot-Starter还包括了一些安全性的特性,如基于令牌的授权和XSS保护,可以帮助您保持您的Websocket应用程序安全。 总的来说,Netty-WebSocket-Spring-Boot-Starter提供了一种快速和易于使用的方式来构建Websocket应用程序,使得它成为应用程序开发人员的有用工具。 ### 回答2: netty-websocket-spring-boot-starter 是一个开源的 Java Web 开发工具包,主要基于 Netty 框架实现了 WebSocket 协议的支持,同时集成了 Spring Boot 框架,使得开发者可以更加方便地搭建 WebSocket 服务器。 该工具包提供了 WebSocketServer 配置类,通过在 Spring Boot 的启动配置类中调用 WebSocketServer 配置类,即可启动 WebSocket 服务器。同时,该工具包还提供了多种配置参数,如端口号、URI 路径、SSL 配置、认证配置等等,可以根据业务需求进行自定义配置。 此外,该工具包还提供了一些可扩展的接口和抽象类,如 WebSocketHandler、ChannelHandlerAdapter 等,可以通过继承和实现这些接口和抽象类来实现业务逻辑的处理和拓展。 总的来说,netty-websocket-spring-boot-starter 提供了一个高效、简单、易用的 WebSocket 服务器开发框架,可以减少开发者的开发成本和工作量。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值