Netty网络聊天室完整代码实现
Netty服务端:
package cn.zhangxueliang.netty.chat;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.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;//聊天程序服务器端
public class ChatServer {private int port; //服务器端端口号public ChatServer(int port) {this.port = port;}public void run() throws Exception {EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch) {ChannelPipeline pipeline=ch.pipeline();//往pipeline链中添加一个解码器pipeline.addLast("decoder",new StringDecoder());//往pipeline链中添加一个编码器pipeline.addLast("encoder",new StringEncoder());//往pipeline链中添加自定义的handler(业务处理类)pipeline.addLast(new ChatServerHandler());}});System.out.println("Netty Chat Server启动......");ChannelFuture f = b.bind(port).sync();f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();bossGroup.shutdownGracefully();System.out.println("Netty Chat Server关闭......");}}public static void main(String[] args) throws Exception {new ChatServer(9999).run();}
}
Netty服务端自定义handler:
package cn.zhangxueliang.netty.chat;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;import java.util.ArrayList;
import java.util.List;//自定义一个服务器端业务处理类
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {public static List<Channel> channels = new ArrayList<>();@Override //通道就绪public void channelActive(ChannelHandlerContext ctx) {Channel inChannel=ctx.channel();channels.add(inChannel);System.out.println("[Server]:"+inChannel.remoteAddress().toString().substring(1)+"上线");}@Override //通道未就绪public void channelInactive(ChannelHandlerContext ctx) {Channel inChannel=ctx.channel();channels.remove(inChannel);System.out.println("[Server]:"+inChannel.remoteAddress().toString().substring(1)+"离线");}@Override //读取数据protected void channelRead0(ChannelHandlerContext ctx, String s) {Channel inChannel=ctx.channel();for(Channel channel:channels){if(channel!=inChannel){channel.writeAndFlush("["+inChannel.remoteAddress().toString().substring(1)+"]"+"说:"+s+"\n");}}}}
Netty客户端:
package cn.zhangxueliang.netty.chat;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.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;//聊天程序客户端
public class ChatClient {private final String host; //服务器端IP地址private final int port; //服务器端端口号public ChatClient(String host, int port) {this.host = host;this.port = port;}public void run(){EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch){ChannelPipeline pipeline=ch.pipeline();//往pipeline链中添加一个解码器pipeline.addLast("decoder",new StringDecoder());//往pipeline链中添加一个编码器pipeline.addLast("encoder",new StringEncoder());//往pipeline链中添加自定义的handler(业务处理类)pipeline.addLast(new ChatClientHandler());}});ChannelFuture cf=bootstrap.connect(host,port).sync();Channel channel=cf.channel();System.out.println("------"+channel.localAddress().toString().substring(1)+"------");Scanner scanner=new Scanner(System.in);while (scanner.hasNextLine()){String msg=scanner.nextLine();channel.writeAndFlush(msg+"\r\n");}} catch (Exception e) {e.printStackTrace();} finally {group.shutdownGracefully();}}public static void main(String[] args) throws Exception {new ChatClient("127.0.0.1",9999).run();}
}
Netty客户端handler:
package cn.zhangxueliang.netty.chat;import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;//自定义一个客户端业务处理类
public class ChatClientHandler extends SimpleChannelInboundHandler<String> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {System.out.println(s.trim());}
}
Netty网络聊天室完整代码实现相关推荐
- Java NIO示例:多人网络聊天室完整代码
服务端: package cn.zhangxueliang.herostory.chatroom;import java.io.IOException; import java.net.InetSo ...
- QQ版网络聊天室完整项目+MFC\C++\C(更改服务器IP可实现异机沟通)
QQ版网络聊天室完整项目+MFC\C++\C 资源地址1 资源地址2 项目简介 服务器端部分代码 客户端响应部分代码 数据库连接 理论~ 实例展示 资源地址1 https://github.com/M ...
- windows网络编程 ---网络聊天室(1)
文章目录 一个简单的网络聊天室 服务器端 代码 客户端 代码 一个简单的网络聊天室 运行如下: 只是实现了一个简单的通信功能,下一节我们再来讨论的IO/CP模型 服务器端 初始化网络环境 int WS ...
- [NUAA]Python用UDP协议建立带有私聊功能的网络聊天室-建立聊天工具
文章目录 前言 1.网络聊天室的基本架构是什么? 1.1 客户端和服务器的架构 1.2 通信协议的选择以及多线程通信 1.2.1 多线程通信 1.2.2 通信协议选择 1.3 前后端功能设计思路 1. ...
- 【完整代码及文档】基于Java的网络聊天室系统的设计与实现
摘 要 计算机从出现到现在有了飞速的发展,现阶段的计算机已经不单单是用于进行运算的独立的个体了,跟随计算机一同发展的还有互联网技术,经过了长久的发展,互联网技术有了日新月异的发展,它的发展速度和计算机 ...
- python基于udp的网络聊天室再用tkinter显示_Python实现网络聊天室的示例代码(支持多人聊天与私聊)...
实验名称: 网络聊天室 功能: i. 掌握利用Socket进行编程的技术 ii. 掌握多线程技术,保证双方可以同时发送 iii. 建立聊天工具 iv. 可以和单人聊天 v. 可以和多个人同时进行聊天 ...
- 仿微信的网络聊天室项目开发【完整源码讲解】
目录 总体开发思路 服务器端 服务器界面设计 建立TCP服务器端通信 建立服务器消息发送输出流 建立服务器消息接收输入流 建立服务器实时消息通信线程 设置服务器通信自由断开 客户端 客户端界面设计 建 ...
- C++网络:IO复用epoll服务器-附带网络聊天室代码实例
//! //! C++网络:IO复用epoll服务器-附带网络聊天室代码实例 //! //! ===== IO复用简介 ===== //! 众所周知,在LINUX中有一切皆文件的说法,将文件视为一种I ...
- Netty网络聊天(一) 聊天室实战
之前做过一个IM的项目,里面涉及了基本的聊天功能,所以注意这系列的文章不是练习,不含基础和逐步学习的部分,直接开始实战和思想引导,基础部分需要额外的去补充,我有精力的话可以后续出一系列的文章. 为什么 ...
最新文章
- 为什么华为在发布会不提鸿蒙,华为又要开发布会?这次没有手机,鸿蒙系统要当主角!...
- 解析oracle的rownum
- scala学习笔记-Array、ArrayBuffer以及遍历数组(7)
- 杭州·云栖大会宣布多款核心云产品降价,最高降幅达90%
- 【嵌入式Linux】嵌入式Linux驱动开发基础知识之设备树模型
- JS—图片压缩上传(单张) 1
- W3C小组宣布:HTML5标准制定完成
- FRR BGP协议分析9 -- FLOW SPEC
- usb_modeswitch下载与安装
- SMOTE算法原理及Python代码实现
- 163的邮箱怎么注册?163的邮箱格式怎么填写?
- Adobe Photoshop CC2018软件安装教程
- 16S rRNA全长测序揭示中国重度污染河口细菌群落的时空动态
- 成长的路上每一步都需要自己去用心体会!
- Python办公——三行代码拆分表格
- 怎么把音乐中的伴奏提取出来?这几个方法值得尝试一番
- 工信部于佳宁:区块链要服务实体经济
- SMPL模型及源码解读
- 三端双向可控硅(triac)
- CF711C三维DP