本文介绍如何使用socket.io库快速轻松地构建网络在线聊天室。 前端没有使用框架。 后端使用express框架构建简单的后端。
socket.io库本质上是基于websocket封装的。 更改了一问一答的格式:以前只能在前端发送请求,而后端无法向前端返回消息。 后端也实现了向前端积极推送信息的前后双向通信。 websocket特别适合在线聊天和实时交互的场景。 已经广泛用于直播平台、视频平台等。
本论文的实现:最基本的前后信息交流。
代码地址: https://github.com/bill mian/socket io-chat
技术堆栈:前端html socketio后端express框架首先创建两个文件: index.html和index.js
index.html文件
! doctypehtmlhtmllang=' en ' headmetacharset=' utf-8 '/metaname=' viewport ' content=' width=device-width, initial-scale=1.0 '/title文档/title/head body/bodyscriptsrc='/socket.io/socket.io.js '/script scriript socket.on(Broadcastmessage ),) msg )={ console.log ) )后端返回的消息),msg ); 渲染内容(msg; ); 在/script/html index.js文件中:
首先使用npm安装库socket.io express
npminstallsocket.io express---- savevarexpress=require (' express ); var app=express (; varhttp=require(http ).createserver ) ) app; vario=require(socket.io ) ) http; app.get () (/)、(req,res ) ) RES.sendfile ) __dirname )/index.html ); ); io.on(connection ),) socket ) ) socket.on ) ) newchatmessage ),) msg ) console.log ) message3360 ) msg io.emit ); ); http.listen(3000,)={console.log ) ) listeningon*:3000; ); 然后在文件目录中运行
node index.js,在浏览器中打开http://localhost:3000
然后用F12打开控制台就可以看到了
前端输出了来自后端的消息
返回到运行nodejs的终端
可以看到后端也收到了前端的消息。
至此,我们实现了使用socketio前后的网络套接字的交互。