2024年09月18日 建站教程
如何利用nodejs语法做一个即时通讯功能?下面web建站小编给大家简单介绍一下具体实现代码!
创建服务器
const app = require('express')(); const server = require('http').createServer(app); const io = require('socket.io')(server); const port = process.env.PORT || 3000; server.listen(port, () => { console.log(`Server listening at http://localhost:${port}`); });
监听连接和断开事件,发送消息
io.on('connection', (socket) => { console.log('a user connected'); socket.on('disconnect', () => { console.log('user disconnected'); }); socket.on('chat message', (msg) => { console.log('message: ' + msg); io.emit('chat message', msg); }); });
客户端页面代码
<html> <head> <title>Chat Room</title> </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> <script src="/static/socket.io/socket.io.js"></script> <script> const socket = io(); const form = document.querySelector('form'); const input = document.querySelector('#m'); const messages = document.querySelector('#messages'); form.addEventListener('submit', (e) => { e.preventDefault(); // 防止页面跳转 socket.emit('chat message', input.value); // 将消息发送给服务器 input.value = ''; // 清空消息框 return false; }); socket.on('chat message', (msg) => { const li = document.createElement('li'); // 创建新条目 li.textContent = msg; // 设置新条目的文本内容 messages.appendChild(li); // 将新条目添加到列表中 }); </script> </body> </html>
本文链接:http://so.lmcjl.com/news/13330/