javascript Socket.io Starter

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Socket.io Starter相关的知识,希望对你有一定的参考价值。

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
 
app.use(express.static(__dirname + '/'));
app.get('/', function (req, res) {
    res.render('index');
});

// user connects
io.on('connection', function(socket){
    // function sendMessage is called by frontend
    socket.on('sendMessage', function(message){
    
            // message is pushed to all connected sockets
            io.emit('getMessage', message);
        }
    });
});
 
//_____Start server_____/
http.listen(8080, function () {
    console.log('listening on *:8080');
});
// <script src="/socket.io/socket.io.js"></script>
// needs to be included in .html
 
var socket = io();
 
document.body.addEventListener('click', function() {
  // Hallo Welt is pushed to backend on body click
  socket.emit('sendMessage', "Hallo Welt");
}, true);
 
// Message is received from backend
socket.on('getMessage', function(msg){
  console.log(msg);
});

以上是关于javascript Socket.io Starter的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript中对socket.io的订阅太多

socket.io javascript客户端在重新启动服务器后无法重新连接

javascript Socket.io Starter

javascript socket.io的快速备忘单

javascript Socket.io广播

如何使用 Socket.io 和 emscripten 使用 javascript 库?