基于express+socket.io
express框架直接安装后得到模板
这是socket官网的例子: https://socket.io/get-started/chat
/** * Module dependencies. */ var app = require('../app'); var debug = require('debug')('server:server'); var http = require('http'); const { Server } = require("socket.io"); const users = {}; /** * Get port from environment and store in Express. */ var port = normalizePort(process.env.PORT || '8888'); app.set('port', port); /** * Create HTTP server. */ var server = http.createServer(app); // 解决跨域问题 const io = new Server(server, { allowEIO3: true, cors: { origin: "*", // from the screenshot you provided methods: ["GET", "POST"] } }); io.on('connection', (socket) => { // 可以发送初始化消息 ---- socket.on('username', (username) => { // 用对应的 socked.id 将用户姓名存入 users[socket.id] = username // 广播给所有的用户 socket.broadcast.emit('welcome', `欢迎<span>${username}</span>来到聊天室`); // 传送自己 socket.emit('welcome', `欢迎<span>${username}</span>来到聊天室`); }) socket.on('chat message', (msg) => { socket.broadcast.emit('message', `${users[socket.id]}:${msg}`); socket.emit('message', `${users[socket.id]}:${msg}`); }); }); /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on('error', onError); server.on('listening', onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('Listening on ' + bind); }; module.exports = io
html 文件
<!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; } .hint { height: 20px; line-height: 20px; font-size: 16px; color: #333; } .hint span { color: red; } </style> </head> <body> <ul id="messages"></ul> <form id="form"> <input id="input" autocomplete="off" /><button>Send</button> </form> <!-- ./node_modules/socket.io/socket.io.js --> <script src="http://localhost:8888/socket.io/socket.io.js"></script> <script> var socket = io('http://localhost:8888'); // 获取用户名称 const username = prompt('请输入您的名称') var form = document.getElementById('form'); var input = document.getElementById('input'); const messages = document.getElementById('messages'); class Message { add(msg, cls) { messages.innerHTML += `<li class=${cls}>${msg}</li>` } } const message = new Message() // 向服务器发送用户名称 socket.emit('username', username); form.addEventListener('submit', function (e) { e.preventDefault(); if (input.value) { socket.emit('chat message', input.value); input.value = ''; } }); socket.on('message', (msg) => { message.add(msg) }) socket.on('welcome', (msg) => { console.log('触发自己') message.add(msg, 'hint') }) </script> </body> </html>