index.js
var http = require("http");
var fs = require("fs");
var ws = require("nodejs-websocket");
http.createServer(function(req,res){ //(请求对象)
fs.readFile(__dirname+req.url,function(err,data){// (错误对象,返回对象)
res.writeHead(200,{"content-type":'text/html;cherset=utf-8'});
res.end(data+"");
})
}).listen(3000); // 3000 http服务
console.log("listen 3000...");
var wsServer = ws.createServer(function(conn){
console.log("有人链接");
conn.on("text",function(str){
console.log("收到:"+str);
broadcast("你好,"+str);
})
})
wsServer.listen(3002); //3002 websocket服务
function broadcast(msg){
for(var i=0;i<wsServer.connections.length;i++){
wsServer.connections[i].sendText(msg);
}
}
a.html
<body>
<input type="text" id="username" />
<button id="btn">发送</button>
<div id="box"></div>
<script>
var btn = document.getElementById("btn");
var username = document.getElementById("username");
var box = document.getElementById("box");
var w = new WebSocket("ws://localhost:3002");
btn.onclick = function(){
w.send(username.value);
}
w.onmessage = function(ev){
var temp = document.createElement("p");
temp.innerHTML = ev.data;
box.appendChild(temp);
}
</script>
</body>
网友评论