How to implement a chat room using the new HTML5 socket.io technology
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>1</title> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"> <style> .user{ color:lightskyblue; cursor: pointer; } </style> </head> <body> <div> <div> <div> <div class="panel panel-default"> <div> <h4 id="欢迎来老王聊天室">欢迎来老王聊天室</h4> </div> <div> <ul id="messageUl"> </ul> </div> <div> <div> <div> <input id="txtMsg" type="text" onkeydown="handleKeyDown(event)"> </div> <div> <button class="btn btn-default" onclick="send()">发送 <span class="glyphicon glyphicon-send"></span> </button> </div> </div> </div> </div> </div> <div> <div class="panel panel-default"> <div> <h4 id="在线用户">在线用户</h4> </div> <div> <ul id="userUl"></ul> </div> <div> <h4 id="在线人数-nbsp">在线人数 0</h4> </div> </div> </div> </div> </div> <script src="/socket.io/socket.io.js"></script> <script> let txtMsg = document.querySelector('#txtMsg'); let onlineUsers = document.querySelector('#onlineUsers'); //此脚本会在window上增加一个io的属性 //http://localhost:8080/=/=空 let socket = io(); //当客户端连接服务器成功之后,向后台发送一个消息,问一下现在有哪些在线用户 socket.on('connect',function(){ socket.emit('users'); }); let messageUl = document.querySelector('#messageUl'); let userUl = document.querySelector('#userUl'); //监听服务器发过来的消息 socket.on('message',function(msgObj){ let li = document.createElement('li'); li.className = 'list-group-item'; li.innerHTML = `${msgObj.username}:${msgObj.content} <span>${new Date(msgObj.createAt).toLocaleString()}</span>`; messageUl.appendChild(li); }); socket.on('userList',function(userList){ userUl.innerHTML = userList.map(item=>( `<li>${item}</li>` )).join(''); countUser(); }); socket.on('user-added',function(username){ let li = document.createElement('li'); li.className = 'list-group-item'; li.innerHTML = `<span>${username}</span>`; userUl.appendChild(li); countUser(); }); function countUser(){ onlineUsers.innerHTML = `在线人数 ${userUl.children.length}`; } //发送事件 function send(){ let content = txtMsg.value;//先拿到聊天的内容 socket.send(content); txtMsg.value = ''; } function handleKeyDown(event){ if(event.keyCode == 13) send(); } //给父级绑定点击事件 事件委托 //要判断点的是span而非别的元素 userUl.addEventListener('click',function(event){ //如果事件源的类名是user的话 if(event.target.className == 'user'){ let username = event.target.innerHTML; txtMsg.value = `@${username} `; } }) </script> </body> </html> <!--npm i express socket.io -S -->
Background node
let express = require('express'); let path = require('path'); let app = express(); app.get('/',function(req,res){ res.sendFile(path.resolve('index.html')); }); let server = require('http').createServer(app); //socket.io是依赖http服务器 let io = require('socket.io')(server); //声明一个对象,保存所有的客户端用户名和它们的socket对应关系 let clients = {}; //监听客户端的连接,当连接到来的时候执行此回调函数 io.on('connection',function(socket){ //在函数的内部声明一个变量,叫username let username; //监听客户端的发过来的消息,当消息发过来的时候执行回调函数 socket.on('message',function(data){ if(username){ //判断是公聊还是私聊 let reg = /@([^ ]+) (.+)/; let result = data.match(reg); if(result){//如果result有值则匹配上了 //此处是私聊 let toUser = result[1]; let content = result[2]; clients[toUser] && clients[toUser].send({ username, content, createAt:new Date() }); }else{//没匹配上 //正常发言,向所有的客户端进行广播 io.emit('message',{ username,content:data,createAt:new Date() }); } }else{ username = data;//把这个消息当成用户名 //关联起来 clients[username]= socket; //向所有的客户端广播说有新的用户加入聊天室 io.emit('message',{ username:'系统',content:`欢迎 ${username} 加入聊天室`,createAt:new Date() }); //事件的名字可以自定义 io.emit('user-added',username); } }); //监听客户端发过来的请求,把用户数组返回 socket.on('users',function(){ let userList = Object.keys(clients); socket.emit('userList',userList); }); }); server.listen(8080); /** * 1.实现匿名聊天 * 1. 在客户端里连接上服务器 * 2. 给发送按钮绑定点击事件,当点击此按钮的时候先获取文本框的内容,把文本框的内容发送到后台 * 3. 后台服务器把此消息广播给所有的客户端。 * 4. 所有的客户端收到消息后把此消息在ul列表里显示出来 * 2.实现具名聊天 * 1. 当此用户第一次向服务器发消息的时候 * 2. 服务器会判断此客户端的用户名是否设置过,如果没设置的话就把这个消息当成用户名,以后再发消息的话都会以这个作为用户名,如果设置过了就是正常发言 * 3. 私聊 * 1. 点击某个在线用户,点击后会在输入框里出现 @xxx yyy * 2. 服务收到私聊的请求后会找到xxx对应的客户端向他单个发消息 * 3 * */
The above is the detailed content of How to implement a chat room using the new HTML5 socket.io technology. For more information, please follow other related articles on the PHP Chinese website!

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1
Easy-to-use and free code editor
