web网页在线聊天代码难不难实现?

服务端代码 io.netty netty-all 4.1.25.Final Java代码如下: WebSocketNettyServer 服务启动入口 WebSocketChannelInitializer 自定义处理通道 ChatHandler 消息处理 import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; public class WebSocketNettyServer { public static void main(String[] args) { // 创建两个线程池 NioEventLoopGroup mainGrp = new NioEventLoopGroup(); // 主线程池 NioEventLoopGroup subGrp = new NioEventLoopGroup(); // 从线程池 try { // 创建Netty服务器启动对象 ServerBootstrap serverBootstrap = new ServerBootstrap(); // 初始化服务器启动对象 serverBootstrap // 指定使用上面创建的两个线程池 .group(mainGrp, subGrp) // 指定Netty通道类型 .channel(NioServerSocketChannel.class) // 指定通道初始化器用来加载当Channel收到事件消息后, // 如何进行业务处理 .childHandler(new WebSocketChannelInitializer()); // 绑定服务器端口,以同步的方式启动服务器 ChannelFuture future = serverBootstrap.bind(9090).sync(); // 等待服务器关闭 future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { // 优雅关闭服务器 mainGrp.shutdownGracefully(); subGrp.shutdownGracefully(); } } } import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.stream.ChunkedWriteHandler; /** * 通道初始化器 * 用来加载通道处理器(ChannelHandler) */ public class WebSocketChannelInitializer extends ChannelInitializer { // 初始化通道 // 在这个方法中去加载对应的ChannelHandler protected void initChannel(SocketChannel ch) { // 获取管道,将一个一个的ChannelHandler添加到管道中 ChannelPipeline pipeline = ch.pipeline(); // 添加一个http的编解码器 pipeline.addLast(new HttpServerCodec()); // 添加一个用于支持大数据流的支持 pipeline.addLast(new ChunkedWriteHandler()); // 添加一个聚合器,这个聚合器主要是将HttpMessage聚合成FullHttpRequest/Response pipeline.addLast(new HttpObjectAggregator(1024 * 64)); // 需要指定接收请求的路由 // 必须使用以ws后缀结尾的url才能访问 pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); // 添加自定义的Handler pipeline.addLast(new ChatHandler()); } } 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.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.util.concurrent.GlobalEventExecutor; import java.net.InetSocketAddress; import java.text.SimpleDateFormat; import java.util.Date; public class ChatHandler extends SimpleChannelInboundHandler { // 用来保存所有的客户端连接 private static final ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm"); // 当Channel中有新的事件消息会自动调用 protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) { // 当接收到数据后会自动调用 // 获取客户端发送过来的文本消息 String text = msg.text(); System.out.println("接收到消息数据为:" + text); Channel channel = ctx.channel(); InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.remoteAddress(); String hostName = inetSocketAddress.getHostName(); Integer port = inetSocketAddress.getPort(); String username = String.format("%s:%s", hostName, port); String chatContent = String.format("[%s] [%s] [%s]", sdf.format(new Date()), username, text); for (Channel client : clients) { // 将消息发送到所有的客户端 client.writeAndFlush(new TextWebSocketFrame(chatContent)); } } // 当有新的客户端连接服务器之后,会自动调用这个方法 @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // 将新的通道加入到clients clients.add(ctx.channel()); } } 客户端代码 在线聊天室 接收到的消息:

体验一下 开启两个浏览器标签页作为两个客户端,并发起聊天 聊天室用户: (127.0.0.1:49790) image 聊天室用户: (127.0.0.1:52341) image 后端服务日志 Connected to the target VM, address: '127.0.0.1:58534', transport: 'socket' 接收到消息数据为:上线上线 接收到消息数据为:我等到花都谢了 接收到消息数据为:啥时候来的? 接收到消息数据为:别抬杠了,上分要紧 推荐阅读更多精彩内容 基于WebSocket的在线聊天室(一)前言 去年在tomcat7自带的例子中发现了两个有趣的demo,贪食蛇游戏和画板。很有意思的是打开的几个窗口内容都...anyesu阅读 36,428评论 25赞 86
1、本文档共25页,可阅读全部内容。
2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:19108035856(电话支持时间:9:00-18:30)。
摘 要
通过文字与符号进行实时交谈、聊天,它是一个向整个因特网开放的地方是提供给网民一个交友与娱乐的场所,在聊天室里网民可选择自已的聊天对象,与其进行对话交流,是网民之间相互沟通、交流情感的最佳方式之一。同时它已成为各网站提供的一个服务标准,是吸引网民,提高人气的一个重要方式。HTML语言、java程序设、计使用MyEclipse编辑器、Oracle数据库、tomcat应用程序服务器的使用以及一个网站的整体建设等。掌握网站的基本架构、服务器与数据库的连接等,强化自己的基本设计能力。
关键词:Abstract From the world's first computer born today more than half a century, however, only because it is convenient, quick, practical, has been used in various fields. Along with the
network information resources, the real-time share to become a reality, more important is, it provides a direct interaction, of course, is not only the interaction between the information
transmission, and also include of person-to-person communication, various chat software and online chat is carrying this kind of interaction of the media. With the development of the
Internet, people through the network can more convenient and quick to learn, information exchange and chat system can provide a better communication platform, in this platform, people can
pass words and symbols of conversation, real-time chat, it is a place of open to the Internet, is to provide users with a friend for recreation, in a chat room users can choose our own chat
with object, communication, mutual communication, the Internet is one of the best way to communicate affection. At the same time it has become one of the website provides service standard,
is to attract users, raise popularity is one of important ways. The design of the network chat is designed using the JSP (Java Server) technology to mix, introduces the main functions of
the chat room, a student user registration, chatting online. Through chatrooms with system design, website construction is the basic operation. Contains pages, the establishment and
management, the server database establishment and use etc. Familiar with HTML, Java, MyEclipse use project procedures and Oracle database editors tomcat, application server and the use of a
web site overall construction, etc. Grasp the basic framework, serv

我要回帖

更多关于 web 聊天 的文章

 

随机推荐