nodejs-websocket
// websocket.js
const ws = require('nodejs-websocket')
let clientCount = 0;
let server = ws.createServer(connection => {
clientCount++;
connection.nickname = 'user' + clientCount;
boardCast(connection.nickname + '进入房间');
connection.on('text', function (result) {
console.log('接收消息:', result)
boardCast(connection.nickname + ':' + result + '!!!')
})
connection.on('connect', function (code) {
console.log('接收消息:', code)
})
connection.on('close', function (code) {
boardCast(connection.nickname + '离开了房间');
console.log('接收消息:', code)
})
connection.on('error', function (code) {
console.log('接收消息:', code)
})
}).listen(8001)
function boardCast(mess) {
server.connections.map((con) => {
con.sendText(mess)
});
}
socket,io.js文件:https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js
socket.io优势:
可以直接发送对象
自定义事件方式
我的代码记录
首先下载nodejs
然后下载sublinetext3或者nodepad++或者phpstorm都可以啊
然后安装socket.io ->$ npm install socket.io
在https://socket.io/blog/网页获取到https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js下载保存
在https://socket.io/docs/网页获取到服务端和客户端资料,改良之后如下所示
wsServer.js服务端
var app = require('http').createServer()
var io = require('socket.io')(app)
var PORT = 3000
var clientCount = 0
app.listen(PORT)
io.on('connection',function(socket){
clientCount++
socket.nickname = 'user' + clientCount
io.emit('enter',socket.nickname + 'comes in')
socket.on('message',function(str){
io.emit('message',socket.nickname + "says:" + str)
})
socket.on('disconnect',function(str){
io.emit('leave',socket.nickname + 'left')
})
})
console.log("sebsocket server listening on port" + PORT)
index.html客户端
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>websocket</title>
<script type="text/javascript" src="socket.io.js"></script>
</head>
<body>
<h1>Chat Room</h1>
<input id="sendTxt" type="text" >
<button id="sendBtn">发送</button>
<script type="text/javascript">
var socket = new io("ws://localhost:3000/");
function showMessage(str,type){
var div = document.createElement('div');
div.innerHTML = str;
if(type == "enter"){
div.style.color = "blue";
}else if(type == "leave"){
div.style.color = "red";
}
document.body.appendChild(div);
}
document.getElementById("sendBtn").onclick = function(){
var txt = document.getElementById("sendTxt").value;
if(txt){
socket.emit('message',txt);
}
}
socket.on('enter',function(data){
showMessage(data,'enter');
})
socket.on('message',function(data){
showMessage(data,'message');
})
socket.on('leave',function(data){
showMessage(data,'leave');
})
</script>
</body>
</html>
http://www.webscoket.org/
遇到的错误
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