⡖⠒⠒⠒⠤⢄⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸ ⠀⠀⠀⡼⠀⠀⠀⠀ ⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢶⣲⡴⣗⣲⡦⢤⡏⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⠋⠉⠉⠓⠛⠿⢷⣶⣦⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠇⠀⠀⠀⠀⠀⠀⠘⡇⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡞⠀⠀⠀⠀⠀⠀⠀⢰⠇⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⡴⠊⠉⠳⡄⠀⢀⣀⣀⡀⠀⣸⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢸⠃⠀⠰⠆⣿⡞⠉⠀⠀⠉⠲⡏⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠈⢧⡀⣀⡴⠛⡇⠀⠈⠃⠀⠀⡗⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣱⠃⡴⠙⠢⠤⣀⠤⡾⠁⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⢀⡇⣇⡼⠁⠀⠀⠀⠀⢰⠃⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⣸⢠⣉⣀⡴⠙⠀⠀⠀⣼⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⡏⠀⠈⠁⠀⠀⠀⠀⢀⡇⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢸⠃⠀⠀⠀⠀⠀⠀⠀⡼⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀⣰⠃⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⣀⠤⠚⣶⡀⢠⠄⡰⠃⣠⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⢀⣠⠔⣋⣷⣠⡞⠀⠉⠙⠛⠋⢩⡀⠈⠳⣄⠀⠀⠀⠀⠀⠀⠀
⠀⡏⢴⠋⠁⠀⣸⠁⠀⠀⠀⠀⠀ ⠀⣹⢦⣶⡛⠳⣄⠀⠀⠀⠀⠀
⠀⠙⣌⠳⣄⠀⡇ 不能 ⡏⠀⠀ ⠈⠳⡌⣦⠀⠀⠀⠀
⠀⠀⠈⢳⣈⣻⡇ 白嫖 ⢰⣇⣀⡠⠴⢊⡡⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠳⢿⡇⠀⠀⠀⠀⠀⠀⢸⣻⣶⡶⠊⠁⠀⠀
⠀⠀⠀⠀⠀⢠⠟⠙⠓⠒⠒⠒⠒⢾⡛⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣠⠏⠀⣸⠏⠉⠉⠳⣄⠀⠙⢆⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⡰⠃⠀⡴⠃⠀⠀⠀⠀⠈⢦⡀⠈⠳⡄⠀⠀⠀⠀⠀⠀⠀
⠀⠀⣸⠳⣤⠎⠀⠀⠀⠀⠀⠀⠀⠀⠙⢄⡤⢯⡀⠀⠀⠀⠀⠀⠀
⠀⠐⡇⠸⡅⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⡆⢳⠀⠀⠀⠀⠀⠀
⠀⠀⠹⡄⠹⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣇⠸⡆⠀⠀⠀⠀⠀
⠀⠀⠀⠹⡄⢳⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⡀⣧⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢹⡤⠳⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣷⠚⣆⠀⠀⠀⠀
⠀⠀⠀⡠⠊⠉⠉⢹⡀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡎⠉⠀⠙⢦⡀⠀
⠀⠀⠾⠤⠤⠶⠒⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠙⠒⠲⠤⠽
Node.js
是一个javascript运行环境。它让javascript可以开发后端程序
,实现几乎其他后端语言实现的所有功能,可以与```PHP、Java、Python、.NET、Ruby等后端语言平起平坐。Ryan Dahl
把这V8搬到了服务器上,用于做服务器的软件。Socket编程库 WS
npm : https://www.npmjs.com/package/ws
Mdn : https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket
模块安装 :npm install ws
Http VS WebSocket 图示
WebSocket
WebSocket并不是全新的协议,而是利用了HTTP协议来建立连接。我们来看看WebSocket连接是如何创建的。
WebSocket使用
首先,WebSocket连接必须由浏览器发起
,因为请求协议是一个标准的HTTP请求,格式 ↓
GET ws://localhost:3000/ws/chat HTTP/1.1
Host: localhost //域名
Upgrade: websocket //表示这个连接将要被转换为WebSocket连接;
Connection: Upgrade //表示这个连接将要被转换为WebSocket连接;
Origin: http://localhost:3000
Sec-WebSocket-Key: client-random-string //用于标识这个连接,并非用于加密数据;
Sec-WebSocket-Version: 13 //指定了WebSocket的协议版本。
该请求和普通的HTTP请求有几点不同
不是类似 /path/
,而是以ws:// 开头的地址
;HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: server-random-string
成功回调说明 ↓
101
表示本次连接的HTTP协议即将被更改,更改后的协议状态 Upgrade: websocket
指定的WebSocket协议。一种是文本,一种是二进制数据
。通常,我们可以发送JSON格式的文本,这样,在浏览器处理起来就十分容易。问题
:为什么WebSocket连接可以实现全双工通信而HTTP连接不行呢?实际上HTTP协议是建立在TCP协议之上的,TCP协议本身就实现了全双工通信,但是HTTP协议的请求-应答机制限制了全双工通信
。实现
:安全的WebSocket连接机制和HTTPS类似。首先,浏览器用 wss://xxx 创建WebSocket连接时,会先通过HTTPS创建安全的连接,然后,该HTTPS连接升级为WebSocket连接,底层通信走的仍然是安全的SSL/TLS协议。服务器支持
由于WebSocket是一个协议,服务器具体怎么实现,取决于所用编程语言和框架本身。Node.js本身支持的协议包括TCP协议和HTTP协议,要支持WebSocket协议,需要对Node.js提供的HTTPServer做额外的开发。已经有若干基于Node.js的稳定可靠的WebSocket实现
,我们直接用npm安装使用即可。
服务器
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send("hellow WebSocketServer!")
})
app.listen(3000, () => {
console.log("server start succeed http://127.0.0.1:3000");
})
const WebSocket = require('ws')
const WebSocketServer = WebSocket.WebSocketServer
const wss = new WebSocketServer({ port: 8080 })
wss.on('connection', (ws) => {
ws.addEventListener('open', () => {
console.log("客户端连接成功")
})
ws.addEventListener('message', (event) => {
//wss.clients(保存着所有连接成功的客户端) 转发给其他人,
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send("群发", { binary: false });
}
});
console.log('接收客户端数据: ', event.data);
})
ws.addEventListener('close', (event) => {
console.log("客户端断开连接: " + event);
})
ws.addEventListener('error', (event) => {
console.log("客户端错误: " + event);
})
ws.send('欢迎来到聊天室!')
})
客户端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Socket Server</title>
</head>
<body>
</body>
<script>
const ClientWebSocketServer = new WebSocket("ws://localhost:8080")
ClientWebSocketServer.addEventListener('open', () => {
console.log("连接成功")
ClientWebSocketServer.send("hello server!")
})
ClientWebSocketServer.addEventListener('message', (event) => {
console.log('接收服务器数据: ', event.data);
})
ClientWebSocketServer.addEventListener('close', (event) => {
console.log("服务器断开连接: " + event);
})
ClientWebSocketServer.addEventListener('error', (event) => {
console.log("服务器错误: " + event);
})
</script>
</html>
连接成功
WebSokcetServer客户端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>客户端</title>
</head>
<body>
<h1>聊天室</h1>
<input type="text" id="text"><button id="send">send</button>
<select id="select">
</select>
<script>
//#region 枚举类型
const WebSocketType = {
Error: 0, //错误
GroupList: 1,//获取列表
GroupChat: 2, //群聊
SingleChat: 3 //私聊
}
//#endregion
var select = document.querySelector("#select")
var send = document.querySelector("#send")
var text = document.querySelector("#text")
const ws = new WebSocket(`ws://localhost:8080?token=${localStorage.getItem("token")}`)
//接受信息
ws.onmessage = (msgObj) => {
msgObj = JSON.parse(msgObj.data)
Unpack(msgObj.type)
}
//信息发送
send.onclick = () => {
if (select.value === "all") {
ws.send(Pack(WebSocketType.GroupChat, text.value))
} else {
ws.send(Pack(WebSocketType.SingleChat, text.value, select.value))
}
}
//#region 装包
function Pack(type, data, to) {
return JSON.stringify({
type,
data,
to
})
}
//#endregion
//#region 拆包
function Unpack(type) {
switch (type) {
case WebSocketType.Error: //错误
// 相关处理 如↓
localStorage.removeItem("token") //移除Token
location.href = "/login" //路径重定向
break;
case WebSocketType.GroupList: //数据类型
// 相关处理
break;
case WebSocketType.GroupChat: //群聊
// 相关处理
break;
case WebSocketType.SingleChat: //私聊
// 相关处理
break;
}
//#endregion
}
</script>
</body>
</html>
WebSocketServer服务器
const WebSocket = require('ws');
const JWT = require('../util/JWT');
const WebSocketServer = WebSocket.WebSocketServer
const wss = new WebSocketServer({ port: 8080 });
//#region 枚举类型
const WebSocketType = {
Error: 0, //错误
GroupList: 1,//获取列表
GroupChat: 2, //群聊
SingleChat: 3 //私聊
}
//#endregion
wss.on('connection', function connection(ws, req) {
const myURL = new URL(req.url, "http://127.0.0.1:3000")
//校验token
const payload = JWT.verify(myURL.searchParams.get("token"))
if (payload) {
ws.send(Pack(WebSocketType.GroupChat, null, "欢迎来到聊天室")); //群聊天室
ws.user = payload //储存数据
//群发
sendAll()
} else {
ws.send(Pack(WebSocketType.Error, null, "token过期"))
}
ws.on('message', function message(data) {
// 转发给其他人,
const msgObj = JSON.parse(data)
//拆包处理数据
Unpack(msgObj.type)
});
ws.on("close", () => {
wss.clients.delete(ws.user) //这里不用处理 → 内置会自动处理
sendAll()
})
});
//#region 向所有客户发送信息
function sendAll() {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(Pack(WebSocketType.GroupList, null, JSON.stringify(Array.from(wss.clients).map(item => item.user))))
}
});
}
//#endregion
//#region 装包
function Pack(type, user, data) {
return JSON.stringify({
type,
user,
data
})
}
//#endregion
//#region 拆包
function Unpack(type) {
switch (type) {
case WebSocketType.Error: //错误
// 相关处理 如↓
localStorage.removeItem("token") //移除Token
location.href = "/login" //路径重定向
break;
case WebSocketType.GroupList: //数据类型
// 相关处理
break;
case WebSocketType.GroupChat: //群聊
// 相关处理
break;
case WebSocketType.SingleChat: //私聊
// 相关处理
break;
}
}
//#endregion
说明 : WebSocket 是 Html5 推出的前端可以直接使用的API,不过目前项目中用的还是Socket.io
比较多。Socket.io在浏览器环境下封装了WebSocket, 可以给开发者带来更好的体验,在功能上也更完善。
github : https://github.com/socketio/socket.io#readme
npm : https://www.npmjs.com/package/socketIO
client scr: npm → open Git url → client-dist 获取压缩的JS脚本
安装 :npm install socket.io
const express = require('express')
const app = express()
const path = require('path')
const socketIO = require('socket.io')
const server = require('http').createServer(app)
const io = socketIO(server)
app.use(express.static(path.join(__dirname, 'public')))
io.on('connection', (socket) => {
socket.emit("客户端发送数据", "hellow client!")
socket.on("服务器发送数据", (event) => {
console.log(event);
})
})
server.listen(3000)
const Koa = require('koa')
const app = new Koa()
const socketIO = require('socket.io')
const server = require('http').createServer(app.callback())
const start: (app) => {
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server, { cors: true }); //这里注意开启跨域
io.on('connection', (socket) => {
socket.emit('on1', { name: '小明' })
socket.on('on2', (data) => {
console.log(data);
})
});
return server
},
start(app).listen(3000)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>客户端</title>
<script src="../socketIO.js"></script>
</head>
<body>
Hello Index.js
</body>
<script>
const socket = io("ws://127.0.0.1:3000")
socket.on("客户端发送数据", (event) => {
console.log(event);
})
socket.emit("服务器发送数据", "hellow server!")
</script>
</html>
WebSokcetIOServer客户端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>客户端</title>
<script src="/javascripts/socketio.js"></script> //这里引入需要配置静态文件 不然报错,不知道为什么❓
</head>
<body>
<h1>聊天室</h1>
<h1>当前用户:
<b id="user"></b>
</h1>
<input type="text" id="text"><button id="send">send</button>
<select id="select">
</select>
<!-- 建立socket连接 带着token,后端验证 -->
<script>
//#region 枚举类型
const WebSocketType = {
Error: 0, //错误
GroupList: 1,//获取列表
GroupChat: 2, //群聊
SingleChat: 3 //私聊
}
//#endregion
//获取属性
var select = document.querySelector("#select")
var send = document.querySelector("#send")
var text = document.querySelector("#text")
var user = document.querySelector("#user")
user.innerHTML = localStorage.getItem("username")
//引入socket.io js端
const socket = io(`ws://localhost:3000?token=${localStorage.getItem("token")}`); //默认 连接了localhost
//#region On绑定事件 Emit监听事件
// 群聊
socket.on(WebSocketType.GroupChat, (msg) => {
// 群聊相关处理
})
// 私聊
socket.on(WebSocketType.SingleChat, (msg) => {
// 私聊相关处理
})
//错误
socket.on(WebSocketType.Error, (msg) => {
// 错误相关处理
// 移除token ...
})
//获取数据
socket.on(WebSocketType.GroupList, (msgObj) => {
// 数据相关处理
})
//#endregion
send.onclick = () => {
if (select.value === "all") {
socket.emit(WebSocketType.GroupChat, createMessage(text.value))
} else {
socket.emit(WebSocketType.SingleChat, createMessage(text.value, select.value))
}
}
//#region 装箱
// function createMessage(type, data, to) {
// return JSON.stringify({
// type,
// data,
// to
// })
// }
// ↓↓
function createMessage(data, to) {
return {
data,
to
}
}
//#endregion
</script>
</body>
</html>
WebSokcetIOServer服务器
const JWT = require("../util/JWT")
let Koa = require("koa");
let app = new Koa();
let server = require("http").Server(app.callback());
//启动服务器
function start(server) {
const io = require('socket.io')(server,{cors:true});
io.on('connection', (socket) => {
// token验证 qyery属性在handhake(握手属性里面).query.token
const payload = JWT.verify(socket.handshake.query.token)
if (payload) {
socket.user = payload
//发送 欢迎
socket.emit(WebSocketType.GroupChat, createMessage(null, "欢迎来到聊天室"))
//给所有发送用户列表
sendAll(io)
} else {
socket.emit(WebSocketType.Error, createMessage(null, "token过期"))
}
//发送数据
socket.on(WebSocketType.GroupList, () => {
// console.log(Array.from(io.sockets.sockets).map(item => item[1].user))
socket.emit(WebSocketType.GroupList, createMessage(socket.user, JSON.stringify(
Array.from(io.sockets.sockets).map(item => item[1].user))))
})
//群发
socket.on(WebSocketType.GroupChat, (msg) => {
//给所有人发
io.sockets.emit(WebSocketType.GroupChat, createMessage(socket.user, msg.data))
//除了自己不发,其他人发
// socket.broadcast.emit(WebSocketType.GroupChat,createMessage(socket.user,msg.data))
})
//私聊
socket.on(WebSocketType.SingleChat, (msgObj) => {
Array.from(io.sockets.sockets).forEach(item => {
if (item[1].user.username === msgObj.to) {
item[1].emit(WebSocketType.SingleChat, createMessage(socket.user, msgObj.data))
}
})
})
//断开
socket.on("disconnect", () => {
sendAll(io)
})
});
}
//#region 枚举类型
const WebSocketType = {
Error: 0, //错误
GroupList: 1,//获取列表
GroupChat: 2, //群聊
SingleChat: 3 //私聊
}
//#endregion
function createMessage(user, data) {
return {
user,
data
}
}
//#region 向所有客户发送数据
function sendAll(io) {
console.log(Array.from(io.sockets.sockets).map(item => item[1].user))
io.sockets.emit(WebSocketType.GroupList, createMessage(null, Array.from(io.socketssockets).map(item => item[1].user).filter(item => item)))
}
//#endregion
module.exports = start
<template>
Hellow
</template>
<script>
import {reactive, toRefs} from "vue";
import {onMounted} from "vue";
//自定义模块
import GetGlobalData from "@/utils/GetGlobalData"; //封装函数
export default {
name: "ECM",
setup() {
const data = reactive({
GetGlobalData: null
})
onMounted(() => {
data.GetGlobalData = GetGlobalData()
StartIO()
})
import {io} from 'socket.io-client'
//#region Self封装函数
function StartIO() {
const socket = data.GetGlobalData.io("ws://127.0.0.1:3002")
socket.on('wcao',(data)=>{
console.log(data)
})
socket.emit('wcao1',{name:"小明 "})
}
//#endregion
return {
...toRefs(data)
}
}
}
</script>
<style scoped>
</style>
const webSocketService = {
start: (app) => {
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server, { cors: true });
io.on('connection', (socket) => {
console.log("连接成功!");
socket.emit('wcao', { name: '小明' })
socket.on('wcao1', (data) => {
console.log(data);
})
});
return server
},
WebSocketType: {
getData: 0,
themeType: 1,
globalResponse: 2
},
TurnType: (value) => {
return JSON.stringify(value)
}
}
module.exports = webSocketService
// APP调用
//Socket 操作
const webSocketService = require('./service/web_socket_service')
webSocketService.start(app).listen(3002, () => {
console.log("WebSocket 监听端口 3002 ...");
})
以上是个人学习Node的相关知识点,一点一滴的记录了下来,有问题请评论区指正,共同进步,这才是我写文章的原因之,如果这篇文章对您有帮助请三连支持一波