webscoket基本使用
WebSocket - Web API 接口参考 | MDN
使用node编写webscoket服务
nodejs-webscoket 在github的地址↓
GitHub - sitegui/nodejs-websocket: A node.js module for websocket server and client
ws和socket.io 是wbscket的两个库
仓库地址:learn-webscoket: webscoket学习 ,前台使用原生写法 基于 webscoket 类
ws库+html 实现聊天
后台使用的是ws库:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8088 }); // websocket的端口let i = 0
wss.on('connection', function connection(ws) {i++console.log("当前链接人数是" + i);ws.on('message', function incoming(message) {console.log('服务端接受到数据:', message);message = message.toString()// console.log(message.toString());// 广播给所有用户wss.clients.forEach(function each(client) {if (client.readyState === WebSocket.OPEN) {// client.send(JSON.stringify(message));client.send(message);}});});// ws.send('something');
});
前台 基于WebSocket 类实现:
<!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>Document</title><style></style>
</head><body><input id="message-text" type="text"><button id="send">发送</button><button id="close">关闭</button><div id="message-list"></div>
</body>
<script type="text/javascript">var ws = new WebSocket('ws://localhost:8088');ws.onopen = function (evt) { // 连接建立触发console.log('建立连接,状态:' + ws.readyState);};ws.onmessage = function (evt) { // 服务端返回数据触发// console.log(String.toString(evt.data));var data = JSON.parse(evt.data)console.log(data);console.log("状态:" + ws.readyState + ";服务端返回数据:", data);var list = document.getElementById("message-list");list.insertAdjacentHTML("beforeEnd", `<div>${data.message}</div>`);};ws.onerror = function (evt) { // 通信发生错误触发console.log(evt);console.log('发生错误,状态:' + ws.readyState);};ws.onclose = function (evt) { // 连接关闭触发console.log(evt);console.log("连接关闭,状态:", ws.readyState);};document.getElementById("send").onclick = function () {var val = document.getElementById("message-text").valuevar data = {message: val}console.log(data);ws.send(JSON.stringify(data)); // 推送数据到服务器, 数据类型必须为字符串// console.log('我发送成功了');}document.getElementById("close").onclick = function () {ws.close(); // 关闭连接}
</script></html>
socket.io + html实现聊天(群聊)
参考:scoket.io实现群聊、私聊_小宇宙chris_310的博客-CSDN博客_scoketio
js部分:
const app = require('express')()
const http = require("http").Server(app);
const io = require("socket.io")(http,{cors:true
});http.listen(3000, () => {console.log(`服务启动成功,地址是 http://127.0.0.1:3000`);
})
console.log(__dirname);
app.get('/', (req, res) => {res.sendFile(__dirname + '/groupChat.html')
})io.on("connection", (socket) => {console.log('用户建立了链接');// 接收客户端发来的数据socket.on('chat message', function (msg) {console.log('message:' + msg);io.emit('receiveMessage', msg)})// 如果是断开socket请求,就会触发下面的代码socket.on('disconnect', function () {console.log('user disconnect') })
});
html部分:
<!doctype html>
<html><head><title>Socket.IO chat</title><style>* {margin: 0;padding: 0;box-sizing: border-box;}body {font: 13px Helvetica, Arial;}form {background: #000;padding: 3px;position: fixed;bottom: 0;width: 100%;}form input {border: 0;padding: 10px;width: 80%;margin-right: .5%;}form button {width: 19%;background: rgb(130, 224, 255);border: none;padding: 10px;}#messages {list-style-type: none;margin: 0;padding: 0;}#messages li {padding: 5px 10px;}</style>
</head><body><ul id="messages"></ul><form action=""><input id="m" autocomplete="off" /><button>Send</button></form>
</body>
<!-- <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"integrity="sha384-/KNQL8Nu5gCHLqwqfQjA689Hhoqgi2S84SNUxC3roTe4EhJ9AfLkp8QiQcU8AMzI"crossorigin="anonymous"></script> --><script src="/socket.io/socket.io.js"></script>
<script>// 这样就加载了 socket.io-client。 socket.io-client 暴露了一个 io 全局变量,然后连接服务器。//请注意我们在调用 io() 时没有指定任何 URL,因为它默认将尝试连接到提供当前页面的主机。var username = prompt('请输入用户名')var socket = io('http://127.0.0.1:3000');var form = document.querySelector('form');var val = document.querySelector('#m');var messages = document.querySelector('#messages')// var messages=document.querySelector('#messages')form.onsubmit = function () {var obj = {username: username,mes: val.value}socket.emit('chat message', JSON.stringify(obj));// messages.innerHTML += `// <li style="text-align:right;color:blue;">${val.value}<li>// `;val.value = '';// console.log(obj);// console.log(messages);return false;//阻止表单默认行为}//接收后端发来的消息socket.on('receiveMessage', function (data) {// console.log(data);var obj = JSON.parse(data);if (obj.username == username)//不渲染自己发送的消息return;//渲染别人发送的消息messages.innerHTML += `<li style="text-align:left;color:red;">${obj.username}:${obj.mes}<li>`;})
</script></html>
socket.io + html实现聊天(私聊)
js部分:
const app = require('express')(); // 获取express模块实例
const http = require('http').Server(app); // 将express模块实例作为回调构建http模块实例
const io = require('socket.io')(http, {cors: true
}); // 将http模块实例作为回调构建socket.io模块实例// 使用http模块开启后端服务(原生node+express的结合)
http.listen(3000, function () {console.log('listening on http://127.0.0.1:3000')
})
// 设置路由,构建后端接口
app.get('/', function (req, res) {res.sendFile(__dirname + '/privateChat.html'); // 将根目录下的index.html发送到前端
})
var users = {}; // 保存所有用户的键值对集合
io.on('connection', function (socket) {socket.on('con', function (msg) {var obj = JSON.parse(msg) // 获取连接的用户信息users[obj.username] = socket.id; // 将当前用户名和对应的链接id进行保存console.log('有新的链接,最新用户集合为:', users)})// 接收客户端发来的数据socket.on('chat message', function (msg) {var obj = JSON.parse(msg) // 获取连接的用户信息console.log('obj:', obj)if (users[obj.toWho] == undefined) {let respmes = {usernamez: '系统信息',mes: '抱歉【' + obj.toWho + '】还未上线'}io.to(socket.id).emit('receiveMessage', JSON.stringify(respmes)); // 将消息发给当前用户} else { // 说明目标用户存在let respmes = {usernamez: obj.username,mes: obj.mes}io.to(users[obj.toWho]).emit('receiveMessage', JSON.stringify(respmes)); // 通过id将信息转发给指定的对象}})// 如果是断开socket请求,就会触发下面的代码socket.on('disconnect', function () {console.log('user disconnected')})
})
html部分:
<html><head><title>Socket.IO chat</title><style>* {margin: 0;padding: 0;box-sizing: border-box;}body {font: 13px Helvetica, Arial;}form {background: #000;padding: 3px;position: fixed;bottom: 0;width: 100%;}form input {border: 0;padding: 10px;width: 80%;margin-right: .5%;}form button {width: 19%;background: rgb(130, 224, 255);border: none;padding: 10px;}#messages {list-style-type: none;margin: 0;padding: 0;}#messages li {padding: 5px 10px;}</style>
</head><body><script src="https://cdn.socket.io/4.5.4/socket.io.min.js"integrity="sha384-/KNQL8Nu5gCHLqwqfQjA689Hhoqgi2S84SNUxC3roTe4EhJ9AfLkp8QiQcU8AMzI"crossorigin="anonymous"></script><!-- <script src="/socket.io/socket.io.js"></script> --><script>// 这样就加载了 socket.io-client。 socket.io-client 暴露了一个 io 全局变量,然后连接服务器。//请注意我们在调用 io() 时没有指定任何 URL,因为它默认将尝试连接到提供当前页面的主机。window.onload = function () {var username = prompt("请输入你的用户名:", "");var who = prompt("你要和谁聊天?:", "");document.body.innerHTML = `<h3>当前用户:${username}, 和${who}聊天中...</h3>` + document.body.innerHTML;var socket = io("http://localhost:3000/");var form = document.querySelector("form");var val = document.querySelector("#m");//先和服务端建立连接let conobj = {username: username,toWho: who,}socket.emit('con', JSON.stringify(conobj));//表单提交事件form.onsubmit = function () {let obj = {username: username,toWho: who,mes: val.value}socket.emit('chat message', JSON.stringify(obj));// messages.innerHTML += `// <li style="text-align:right;color:blue;">${val.value}<li>`;val.value = "";return false;}//接收后端发来的消息socket.on("receiveMessage", function (data) {var obj = JSON.parse(data);console.log(obj)if (obj.username == username) return; //不接受自己发的消息messages.innerHTML += `
<li style="text-align:left;color:red;">${obj.usernamez}:${obj.mes}<li>`;})}</script><ul id="messages"></ul><form action=""><input id="m" autocomplete="off" /><button>Send</button></form>
</body></html>