netty简单实现聊天功能

1、服务端

package mynetty_study.netty.nettytest;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 *类名:NettyServer.java
 *类的描述信息:
 *创建时间:上午11:42:00
 **/
public class NettyServer {
	
	//创建用于接收客户端连接请求
	private static final EventLoopGroup bossGroup = new NioEventLoopGroup();
	//创建用于处理Socketchannel输入输出的
	private static final EventLoopGroup handleGroup = new NioEventLoopGroup();
	private static final int port = 8888;
	
	public static void main(String[] args) {
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		//设置group
		serverBootstrap.group(bossGroup, handleGroup)
		//设置要被实例化的类
		.channel(NioServerSocketChannel.class)
		//设置Channel处理器
		.childHandler(new ChannelInitializer<Channel>(){

			@Override
			protected void initChannel(Channel ch) throws Exception {
				ChannelPipeline cp = ch.pipeline();
				//添加帧限定符来防止粘包
				//粘包:
				//	只有TCP有粘包现象,UDP永远不会粘包
				//	发送端需要等缓冲区满才发送出去,造成粘包(发送数据时间间隔很短,数据了很小,会当做一个包发出去,产生粘包)
				//	接收方不及时接收缓冲区的包,造成多个包接收(客户端发送了一段数据,服务端只收了一小部分,服务端下次再收的时候还是从缓冲区拿上次遗留的数据,产生粘包)
				cp.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4))
				//配置编解码
				.addLast(new StringDecoder(CharsetUtil.UTF_8))
				.addLast(new StringEncoder(CharsetUtil.UTF_8))
				//配置业务逻辑实现类
				.addLast(new TCPServerHandler());
				
			}
			
		});
		
		try {
			ChannelFuture future = serverBootstrap.bind(port).sync();
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		
	}
}
package mynetty_study.netty.nettytest;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
/**
 *类名:TCPServerHandler.java
 *类的描述信息:
 *服务相关的设置的代码写完之后,我们再来编写主要的业务代码。 使⽤用Netty编写 [业务层 ]的代码,
 *我们需要继承 ChannelInboundHandlerAdapter 或 SimpleChannelInboundHandler 类,在这
 *里里顺便便说下它们两的区别吧。 继承 SimpleChannelInboundHandler 类之后,会在接收到数据后会
 *自动 release 掉数据占⽤用的 Bytebuffer 资源。并且继承该类需要指定数据格式。 ⽽而继
 *承ChannelInboundHandlerAdapter 则不不会⾃自动释放,需要⼿手动调⽤用
 *ReferenceCountUtil.release() 等⽅方法进⾏行行释放。继承该类不不需要指定数据格式。 所以在这⾥里里,个⼈人
 *推荐服务端继承 ChannelInboundHandlerAdapter ,⼿手动进⾏行行释放,防⽌止数据未处理理完就⾃自动释放
 *了了。而且服务端可能有多个客户端进⾏行行连接,并且每⼀一个客户端请求的数据格式都不不⼀一致,这时便便可
 *以进行相应的处理理。 客户端根据情况可以继承 SimpleChannelInboundHandler 类。好处是直接指
 *定好传输的数据格式,就不不需要再进⾏行行格式的转换了了
 *创建时间:下午2:28:03
 **/
public class TCPServerHandler extends ChannelInboundHandlerAdapter {

	//连接成功时候执行的操作
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//System.out.println("连接成功");
	}
	//执行读写
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		//执行会话
		System.out.println("客户端:"+msg);
		System.out.print("我:");
		Scanner scan = new Scanner(System.in);
		String str = scan.next();
		ctx.channel().writeAndFlush(str);
		ctx.close();
	}
	//异常处理
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		System.out.println("打印异常日志:"+cause.getStackTrace());
	}
	
}

2、客户端

package mynetty_study.netty.nettytest;

import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.util.Scanner;

import mynetty_study.netty.netty1.MyClient;

/**
 *类名:NettyClient.java
 *类的描述信息:
 *创建时间:下午7:55:30
 **/
public class NettyClient implements Runnable{

	private static final int port = 8888;
	private static final String ip = "127.0.0.1";

	
	public static void main(String[] args) {
		new Thread(new NettyClient()).start();
	}

	@Override
	public void run() {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap boot = new Bootstrap();
			//设置group
			boot.group(group);
			//设置要被实例化的类
			boot.channel(NioSocketChannel.class)
			//设置TCP方式的通信
			.option(ChannelOption.TCP_NODELAY, true)
			//设置SocketChannel处理器
			.handler(new ChannelInitializer<SocketChannel>(){

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ChannelPipeline pipeline = ch.pipeline();
					pipeline.addLast(new LengthFieldPrepender(4));
					//设置编解码
					pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
					pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
					pipeline.addLast(new TcpClient());
				}

			});



			//执行会话
			boolean check = true;
			while(check){
				ChannelFuture future = boot.connect(ip, port).sync();
				System.out.print("我:");
				Scanner sc=new Scanner(System.in);
				String str=sc.next();
				future.channel().writeAndFlush(str);
				future.channel().closeFuture().sync();
				if(str.equals("bye")){
					check=false;
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			group.shutdownGracefully();
		}




	}

}
package mynetty_study.netty.nettytest;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TcpClient extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		System.out.println("服务端:"+msg);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		System.out.println(cause.getStackTrace());
	}

}

3、效果

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先,需要了解什么是NettyNetty是一个异步事件驱动的网络应用框架,用于快速开发可维护的高性能协议服务器和客户端。 接下来,我们可以开始实现聊天功能。一个简单聊天室应该具备以下功能: 1. 用户连接和断开连接的处理; 2. 用户发送消息和接收消息的处理; 3. 消息广播给所有在线用户。 下面是一个简单实现: 1. 用户连接和断开连接的处理 Netty提供了ChannelHandlerAdapter和ChannelInboundHandlerAdapter两个抽象类,我们可以继承其中一个来实现自己的Handler。这里我们使用ChannelInboundHandlerAdapter。 ```java public class ChatServerHandler extends ChannelInboundHandlerAdapter { // 用户列表,用于保存所有连接的用户 private static List<Channel> channels = new ArrayList<>(); // 新用户连接时,将连接加入用户列表 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " 上线了"); } // 用户断开连接时,将连接从用户列表中移除 @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { channels.remove(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " 下线了"); } } ``` 2. 用户发送消息和接收消息的处理 Netty的数据传输是通过ByteBuf来实现的,因此我们需要将ByteBuf转换为字符串进行处理。 ```java public class ChatServerHandler extends ChannelInboundHandlerAdapter { // 用户列表,用于保存所有连接的用户 private static List<Channel> channels = new ArrayList<>(); // 新用户连接时,将连接加入用户列表 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " 上线了"); } // 用户断开连接时,将连接从用户列表中移除 @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { channels.remove(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " 下线了"); } // 接收用户发送的消息并处理 @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; String received = buf.toString(CharsetUtil.UTF_8); System.out.println(ctx.channel().remoteAddress() + ": " + received); broadcast(ctx, received); } // 将消息广播给所有在线用户 private void broadcast(ChannelHandlerContext ctx, String msg) { for (Channel channel : channels) { if (channel != ctx.channel()) { channel.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8)); } } } } ``` 3. 消息广播给所有在线用户 我们可以使用broadcast方法将接收到的消息广播给所有在线用户。 ```java public class ChatServerHandler extends ChannelInboundHandlerAdapter { // 用户列表,用于保存所有连接的用户 private static List<Channel> channels = new ArrayList<>(); // 新用户连接时,将连接加入用户列表 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " 上线了"); } // 用户断开连接时,将连接从用户列表中移除 @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { channels.remove(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " 下线了"); } // 接收用户发送的消息并处理 @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; String received = buf.toString(CharsetUtil.UTF_8); System.out.println(ctx.channel().remoteAddress() + ": " + received); broadcast(ctx, received); } // 将消息广播给所有在线用户 private void broadcast(ChannelHandlerContext ctx, String msg) { for (Channel channel : channels) { if (channel != ctx.channel()) { channel.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8)); } } } } ``` 接下来我们需要编写一个启动类,用于启动聊天室服务器。 ```java public class ChatServer { public static void main(String[] args) throws Exception { // 创建EventLoopGroup EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { // 创建ServerBootstrap ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ChatServerHandler()); } }); // 启动服务器 ChannelFuture channelFuture = serverBootstrap.bind(8888).sync(); System.out.println("服务器启动成功"); // 关闭服务器 channelFuture.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } ``` 现在,我们就完成了一个简单聊天室服务器。可以通过运行ChatServer类启动服务器,然后使用telnet命令连接服务器进行聊天。 ```sh telnet localhost 8888 ``` 输入发送的消息,即可将消息广播给所有在线用户。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值