聊天室页面-->index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>初识WebSocket</title>
</head>
<body>
<h1>Chat Room</h1>
<div style="margin-top: 30px;margin-left:30px">
<input type="text" id="info">
<button id="send">send</button>
<div id="notice"></div>
<div id="msg"></div>
</div>
</body>
<script src="websocket.js"></script>
</html>
发送请求与接受响应-->websocket.js
var info = document.getElementById("info");
var send= document.getElementById("send");
var notice = document.getElementById("notice");
var msg = document.getElementById("msg"); var ws = new WebSocket("ws://localhost:8001");
ws.onopen = function(){
notice.innerHTML = "websocket connected";
}
ws.onclose = function(){
notice.innerHTML = "closed"
}
ws.onmessage = function(response){
console.log(response);
//收到message后,创建一个div,保存消息,并追加到msg中。
var div = document.createElement("div");
var json = JSON.parse(response.data);
switch(json.type){
case "enter":
div.innerHTML = "<font color='blue'>" + json.data + "</font>";
break;
case "message":
div.innerHTML = "<font color='orange'>" + json.data + "</font>";
break;
default:
div.innerHTML = "<font color='brown'>" + json.data + "</font>";
break;
}
msg.appendChild(div);
}
send.onclick = function(){
ws.send(info.value)
}
WebSocket服务器-->server.js
var ws = require("nodejs-websocket") var port = 8001;
var count = 0;//client的计数器 function broadcast(server, msg) {
//server.connections是一个数组,保存着所有client
server.connections.forEach(function (connection) {
connection.sendText(msg);
});
}
var server = ws.createServer(function (conn) {
console.log("New connection");
count++;
conn.nickname = "user" + count;
var msg = {
"type" : "enter",
"data" : conn.nickname + " come in"
}
broadcast(server, JSON.stringify(msg));
conn.on("text", function (str) {
console.log("Received From: "+ conn.nickname + " ---- Data:" + str);
var msg = {
"type" : "message",
"data" : conn.nickname + ": " + str
}
broadcast(server, JSON.stringify(msg));
});
conn.on("close", function (code, reason) {
var msg = {
"type" : "left",
"data" : conn.nickname + " left the room"
}
broadcast(server, JSON.stringify(msg));
console.log("Connection closed");
});
conn.on("error", function(err){
console.log("some accident happend");
console.log(err);
});
}); console.log("websocket started , listening " + port)
server.listen(port)