遇到的错误
The 'Access-Control-Allow-Origin' header has a value 'null' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access
解决方法:将所有环境搭载HTTP服务器上
安装
npm install socket.io
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script> <title>Chat Room Demo</title> </head> <body> <h1>Chat Room Based on Socket.io</h1> SEND: <input type="text" id="sendText" /> <button id="sendBtn">Send</button> <br /> RECV: <span id="recv"></span> <script> var socket = io("ws://localhost:8001/") function showMsg(str, type) { var div = document.createElement('div'); div.innerHTML = str if (type == "enter") { div.style.color = 'blue'; } else if (type == "disconnect") { div.style.color = 'red'; } document.body.appendChild(div); } document.getElementById("sendBtn").onclick = function () { var txt = document.getElementById("sendText").value; if (txt) { socket.emit('message', txt); } } socket.on('enter', function (data) { showMsg(data, 'enter'); }); socket.on('message', function (data) { showMsg(data, 'message'); }); socket.on('disconnect', function (data) { showMsg(data, 'disconnect'); }); </script> </body> </html>
app.js
const POST = 8001; var app = require('http').createServer(); var io = require('socket.io')(app); var userCount = 0; app.listen(POST); console.log("WebSocket Server Linstening on POST:" + POST); io.on('connection', function (socket) { userCount++; socket.nickname = "USER" + userCount; console.log("[ENTER]\t", socket.nickname); io.emit("enter", socket.nickname + ' ENTER'); socket.on("message", function (str) { io.emit("message", socket.nickname + ' SAYS: ' + str); console.log("[MSG]\t", socket.nickname, " \t SAY: ", str); }); socket.on("disconnect", function () { io.emit("disconnect", socket.nickname + ' LEFT') console.log("[LEFT]\t", socket.nickname); }); });
启动:
node app.js