Socket.io 是一个基于 Node.js 的实时通讯库,可以在浏览器和服务器之间建立实时、双向、事件驱动的通讯。它封装了 WebSocket 和轮询等多种实现方式,可以在不同的环境下使用。
安装和使用
在使用 Socket.io 前,需要先安装它。可以通过 npm 安装:
npm install socket.io
在服务器端,需要使用以下代码启动 Socket.io:
const io = require('socket.io')(server);其中,server 是一个 http 服务器对象,可以使用 Node.js 的 http 模块创建。
在客户端,需要引入 Socket.io 的客户端库:
<script src="/socket.io/socket.io.js"></script>
然后,可以使用以下代码连接服务器:
const socket = io();
实现实时通讯
在连接成功后,客户端和服务器可以相互发送事件。事件可以是预定义的,也可以是自定义的。以下是一个简单的聊天室的例子:
服务器端代码
// www.javascriptcn.com code example
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
fs.readFile(__dirname + '/index.html', (err, data) => {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
});
const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});客户端代码
// www.javascriptcn.com code example
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<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: 90%;
margin-right: 0.5%;
}
form button {
width: 9%;
background: rgb(130, 224, 255);
border: none;
padding: 10px;
}
#messages {
list-style-type: none;
margin: 0;
padding: 0;
}
#messages li {
padding: 5px 10px;
}
#messages li:nth-child(odd) {
background: #eee;
}
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/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();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', (msg) => {
const li = document.createElement('li');
li.textContent = msg;
messages.appendChild(li);
});
</script>
</body>
</html>在这个例子中,服务器监听了 'connection' 事件,当有客户端连接时,打印一条日志,并监听 'chat message' 事件,当收到客户端发送的消息时,打印一条日志,并通过 io.emit() 发送给所有连接的客户端。
客户端在发送消息时,通过 socket.emit() 发送消息,同时监听 'chat message' 事件,当收到服务器发送的消息时,将消息添加到页面上。
结语
Socket.io 是一个非常强大的实时通讯库,可以用于构建实时聊天、在线游戏、即时通讯等应用。它封装了底层的实现细节,使得开发者可以更加专注于业务逻辑的实现。同时,Socket.io 也提供了丰富的 API 和事件,可以满足不同的需求。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d13139a941bf7134286746