一、demo要求
1)编写一个Netty个人对个人聊天系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
2)实现单人对单人聊
3)服务器端:可以监测用户上线,离线,并实现消息转发功能。
4)客户端:通过channel可以无阻塞发送消息给对应用户(有服务器转发得到)
5)目的:进一步理解Netty非阻塞网络编程机制。
二、服务器代码
package com.tfq.netty.netty.personalchat;
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 PersonChatServer {
//监听端口
private int port;
public PersonChatServer(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.a

最低0.47元/天 解锁文章
620

被折叠的 条评论
为什么被折叠?



