当前用户:null, 和null聊天中...

webscoket学习

webscoket基本使用 

WebSocket - Web API 接口参考 | MDN

webscoket学习_第1张图片

webscoket学习_第2张图片

 使用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 类实现:





    
    
    
    Document
    



    
    
    
    

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部分:





    Socket.IO chat
    



    

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部分:




    Socket.IO chat
    



    
    
    
    

    你可能感兴趣的:(笔记,html,前端)