Java+Netty 实现即时通讯示例

Java + Netty 实现即时通讯 完整代码示例以及代码注释如下:

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
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;

public class InstantMessagingServer {
    private int port;

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

    public void run() throws Exception {
        // 创建两个EventLoopGroup,用于处理客户端连接和网络IO操作
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 创建ServerBootstrap对象,用于启动服务器
            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup) // 设置两个EventLoopGroup
                    .channel(NioServerSocketChannel.class) // 指定使用NIO传输Channel
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 添加StringDecoder和StringEncoder,用于处理字符串消息的编解码
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            // 添加自定义的处理器
                            ch.pipeline().addLast(new InstantMessagingServerHandler());
                        }
                    });

            // 绑定端口,启动服务器并等待绑定完成
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("Server started on port " + port);

            // 等待服务器的Channel关闭
            future.channel().closeFuture().sync();
        } finally {
            // 优雅地关闭EventLoopGroup
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        InstantMessagingServer server = new InstantMessagingServer(port);
        server.run();
    }
}

class InstantMessagingServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("Received message: " + msg);
        ctx.writeAndFlush("Server received: " + msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 发生异常时关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}
在这个示例中,我们创建了一个InstantMessagingServer类来启动服务器。在run方法中,我们创建了两个NioEventLoopGroup来处理客户端连接和网络IO操作。然后,我们创建了一个ServerBootstrap对象,并设置了两个EventLoopGroup、使用NIO传输Channel和自定义的处理器。最后,我们绑定端口,启动服务器并等待绑定完成。
InstantMessagingServerHandler类是自定义的处理器,继承自SimpleChannelInboundHandler<String>。在channelRead0方法中,我们处理接收到的消息,并通过ctx.writeAndFlush方法将处理结果返回给客户端。在exceptionCaught方法中,我们处理发生的异常,并关闭连接。
注:可以根据需要调整服务器的端口号,以及在channelRead0方法中完善自己接收到的消息的业务逻辑,进行具体操作。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
聊天系统采用客户机/服务器(C/S)地模式来设计,是一个3层地C/S结构:数据库服务器→应用程序服务器端→应用程序客户端,其分层结构如下图所示。系统采用C/S结构,可以将任务合理分配到客户机端和服务器端,从而降低了系统的通讯开销。 1. 客户层 客户层也叫应用表示层,是应用程序地客户接口部分。给聊天工具设计一个客户层具用很多优点,这是因为客户层担负着用户与应用间地对话功能。它用于检查用户的输入数据,显示应用的输出数据。为了使用户能直观的进行操作,客户层需要使用接口。若聊天用户变更,系统只需改写显示控制和数据检查程序即可,而不影响其他两层。数据检查的内容限于数据的形式和值得范围,不包括有关业务的处理逻辑。 2. 服务层 服务层又叫功能层,相当于应用的本体,他是讲具体的业务出路逻辑编入程序中。例如,用户需要检索数据,系统没法将有关检索要求的信息一次性的传送给功能层:而用户登陆后,聊天登录信息是由功能层处理过的检索结果数据,他也是一次性传送给表示层的。在应用设计中,不许避免在表示层和功能层之间进行多次的数据交换,这就需要尽可能进行一次性的业务处理,达到优化整体设计的目的。 3. 数据层 数据层就是DBMS,本聊天工具使用了Microsoft公司的SQL Server2000能迅速执行大量的更新和检索,因此,从功能层传送到数据层的“要求”一般都使用SQL语言
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值