1. 使用http 模块创建服务
const http = require('http');
const { Server } = require('socket.io');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
const io = new Server(server, {
cors: {
origin: "http://localhost:3000", // 允许本地访问
// origin: "*", // 允许所有
methods: ["GET", "POST"]
}
});
io.on('connection', (socket) => {
console.log('a user connected');
});
server.listen(3000, () => {
console.log('server is running on port 3000');
});
H5 测试页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket.io Example</title>
</head>
<body>
<h1>Socket.io Example</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.1.3/socket.io.js"></script>
<script>
const socket = io("http://localhost:3000", { transports: ['websocket'] });
socket.on('connect', () => {
console.log('Connected to server');
});
socket.on('disconnect', () => {
console.log('Disconnected from server');
});
</script>
</body>
</html>
网友评论