nodejs結合Socket.IO實現(xiàn)websocket即時通訊
為什么要用 websocket
websocket 是一種網(wǎng)絡通信協(xié)議,一般用來進行實時通信會使用到。
websocket 協(xié)議和 http 協(xié)議類似,http 協(xié)議有一個缺陷,只能由客戶方端發(fā)起請求,服務端根據(jù)請求 url 和傳過去的參數(shù)返回對應結果
websocket 是雙向通信的,只要 websocket 連接建立起來,可以由客戶端給服務端發(fā)送數(shù)據(jù),也可以由服務端主動給客戶端發(fā)送數(shù)據(jù)
websocket 適用場景:網(wǎng)頁版聊天室,網(wǎng)頁版客服,前后端頻繁交換數(shù)據(jù)的即時通訊場景。
Socket.io
雙向和低延遲的websocket通信包,高性能,高可靠,可伸縮。
(簡單地講,就是將websocket進行封裝和優(yōu)化。)

Socket.IO 是一個庫,可以在瀏覽器和服務器之間實現(xiàn)實時、雙向和基于事件的通信。 它包括:
- server端
- client端

官方網(wǎng)址
https://socket.io/
官方文檔
https://socket.io/docs/v4/
開源項目
以下代碼和時間項目會發(fā)布在開源項目【nodejs-study】,歡迎下載和學習
效果預覽
輸入node app 運行服務之后可以通過 http://localhost:3000/ 進行訪問,如果看到輸出監(jiān)聽3000端口和前端顯示hello world證明項目啟動成功。

前端頁面:一個聊天的UI框,包含發(fā)送和接收功能 http://localhost:3000/test

后臺websocket:監(jiān)聽和答復

app.js
首先需要安裝express和socket.io庫
輸入npm install express --save或者yarn add express
輸入npm install socket.io--save或者yarn add socket,io
接下來實現(xiàn) 對 / 和 /test 兩個路徑的監(jiān)聽
/返回hello world/test返回html連接頁面
socket.on(“chat message”,callback function)
表示開始監(jiān)聽"chat message"通道,只要前后端都是一致的通道即可。
socket.emit(“chat message”, msg.toUpperCase());
表示對這個"chat message"通道進行回復,我們暫時是對英文字母做大寫處理并返回。
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.send('<h1>Hello world</h1>');
});
app.get('/test', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// io.on('connection', (socket) => {
// console.log('a user connected');
// });
//by zhengkai.blog.csdn.net
//處理socket.on信息并socket.emit回復信息
//這里對接收到的msg做大寫處理
io.on('connection', (socket) => {
//Socket.io by zhengkai.blog.csdn.net
socket.on('chat message', (msg) => {
console.log('received: ' + msg);
socket.emit("chat message", msg.toUpperCase());
});
});
//監(jiān)聽端口3000
server.listen(3000, () => {
console.log('listening on *:3000');
});
index.html
這做一些樣式處理,并且有以下body內(nèi)容:
- message的ul,可以用來追加li信息,顯示記錄往來
- 一個form表單,用來提交要發(fā)送的信息
script部分而言,首先使用官方的socket.io 的js client , 初始化一個連接,添加監(jiān)聽事件:
- 輸入非空內(nèi)容提交后,發(fā)送信息給websocket后臺,同事也輸出在信息列表
- 接收到信息之后,顯示在信息列表
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
#form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
#input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
#input:focus { outline: none; }
#form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages > li { padding: 0.5rem 1rem; }
#messages > li:nth-child(odd) { background: #efefef; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
</body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
//輸出到屏幕
function addMessage(str){
const li = document.createElement("li")
li.innerHTML=str;
messages.appendChild(li);
}
// console.log(form)
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
//Socket.io by zhengkai.blog.csdn.net
let msg = '發(fā)送消息:'+input.value ;
console.log(msg)
socket.emit('chat message', input.value);
addMessage(msg);
//清空個輸入框
//input.value = '';
}
});
socket.on("chat message", (arg) => {
let msg = '接收消息:'+arg ;
console.log(msg); // world
addMessage(msg);
});
</script>
</html>
到此這篇關于nodejs結合Socket.IO實現(xiàn)websocket即時通訊 的文章就介紹到這了,更多相關node websocket即時通訊 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
node.js中實現(xiàn)token的生成與驗證的操作方法
Token是一種用于在客戶端和服務器之間安全傳輸信息的加密字符串,常用于身份驗證、授權、狀態(tài)管理和安全性,在Node.js中,常用jsonwebtoken庫生成和驗證Token,本文介紹node.js中實現(xiàn)token的生成與驗證的操作方法,感興趣的朋友一起看看吧2025-01-01
Node.js處理I/O數(shù)據(jù)之使用Buffer模塊緩沖數(shù)據(jù)
這篇文章介紹了Node.js使用Buffer模塊緩沖數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07
如何用npm命令刪除開發(fā)項目中的node_modules文件夾
每個項目都會產(chǎn)生一個node_modules,每個node_modules少則幾十兆,多則幾百甚至上千兆,隨著時間的積累,維護項目的增加,整個項目目錄體積會越來越大,這篇文章主要給大家介紹了關于如何用npm命令刪除開發(fā)項目中的node_modules文件夾,需要的朋友可以參考下2023-12-12
Node服務端實戰(zhàn)之操作數(shù)據(jù)庫示例詳解
這篇文章主要為大家介紹了Node服務端實戰(zhàn)之操作數(shù)據(jù)庫示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12

