Netty进阶 -- 非阻塞网络编程 实现群聊+私聊+心跳检测系统

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!
import java.util.concurrent.TimeUnit;

public class GroupChatServer {

// 监听端口

private int port;

public GroupChatServer(int port) {

this.port = port;

}

//编写run方法,处理客户端的请求

public void run() {

//创建两个线程组

EventLoopGroup bossGroup = new NioEventLoopGroup(1);

//Nio核数 * 2

EventLoopGroup workerGroup = new NioEventLoopGroup();

ServerBootstrap bootstrap = new ServerBootstrap();

try {

bootstrap.group(bossGroup, workerGroup)

.channel(NioServerSocketChannel.class)

.option(ChannelOption.SO_BACKLOG, 128)

.childOption(ChannelOption.SO_KEEPALIVE, true)

.childHandler(new ChannelInitializer() {

@Override

protected void initChannel(SocketChannel socketChannel) throws Exception {

//获取pipeline

ChannelPipeline pipeline = socketChannel.pipeline();

//向pipeline加入解码器

pipeline.addLast(“decoder”, new StringDecoder());

//向pipeline加入编码器

pipeline.addLast(“encoder”, new StringEncoder());

//加入自己的业务处理handler

pipeline.addLast(new GroupChatServerHandler());

//加入心跳检测机制

pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));

pipeline.addLast(new HeartbeatServerHandler());

}

});

System.out.println(“netty 服务器启动”);

ChannelFuture future = bootstrap.bind(port).sync();

//监听关闭事件

future.channel().closeFuture().sync();

} catch (Exception e) {

e.printStackTrace();

} finally {

bossGroup.shutdownGracefully();

workerGroup.shutdownGracefully();

}

}

public static void main(String[] args) {

GroupChatServer groupChatServer = new GroupChatServer(7000);

groupChatServer.run();

}

}

GroupChatServerHandler 服务器自定义handler

package com.wanshi.netty.groupchat;

import io.netty.channel.Channel;

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.SimpleChannelInboundHandler;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

public class GroupChatServerHandler extends SimpleChannelInboundHandler {

//所有的channel存入map集合中,目的是为了私聊好获取用户

private static Map<String,Channel> allChannels = new HashMap<String,Channel>();

//格式化所有日期时间

private SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

//转化日期

private String currentDate = sdf.format(new Date());

/**

  • handlerAdded 表示连接建立,一旦连接建立,第一个被执行

  • 将当前channel加入到map集合

*/

@Override

public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

//获取当前channel

Channel channel = ctx.channel();

//推送客户加入聊天的信息推送给其它在线的客户端

//该方法会将channelGroup中所有的channel遍历并发送消息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值