//app.js
var ws = require('nodejs-websocket');
var server = ws.createServer(function(conn){
console.log('connected');
conn.on('text',function(str){
console.log(str);
//conn.sendText(str);//将接收道德str用sendText方法传给接收到的一个连接
//boardcast(str);//调用广播方法将节后到的传给所有的浏览器
var data = JSON.parse(str);
switch (data.type){
case 'chat':
//boardcast(conn.nickname + '说:' + data.text);
boardcast(JSON.stringify({name:conn.nickname,text:conn.nickname + '说:' + data.text}));
break;
case 'setname':
conn.nickname = data.name;
//boardcast(data.name+'加入了房间');
boardcast(JSON.stringify({text:data.name+'加入了房间',name:conn.nickname}));
break;
}
});
// setTimeout(function(){
// conn.sendText('来自服务端的消息!');
// },3000);
conn.on('close',function(){
boardcast(JSON.stringify({name:conn.nickname,text:conn.nickname+'退出了房间'}));
});
conn.on('error',function(err){
console.log(err);
});
}).listen(2333);
/**
* 这个connections是一个数组包含我们所有的连接
*/
//我们来写一个广播吧
function boardcast(str){
server.connections.forEach((conn) => {
conn.sendText(str);
});
}
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>测试一下websocket</title>
</head>
<body>
<input id='name' type='text'>
<button id='setname' type='button'>设置</button>
<input id='text' type='text'>
<button id='btn' type='submit'>发送</button>
<div id="root"></div>
<script>
var ws = null;
document.getElementById('setname').onclick = function() {
var name = document.getElementById('name').value;
if(name === null){
alert('注意用户名不能为空');
}
console.log(name);
ws =new WebSocket('ws://localhost:2333');
ws.onopen = function (){
ws.send(JSON.stringify({name:name,type:'setname'}));
document.getElementById('btn').onclick = () => {
//console.log(document.getElementById('text').value);
ws.send(JSON.stringify({text:document.getElementById('text').value,type:'chat'}));
}
}
ws.onmessage = function (e){
//console.log(e.data);
//document.body.innerHTML += '<p>'+e.data + '</p>';
// var p =document.createElement('p');
// p.innerHTML = e.data;
document.getElementById('root').appendChild(createChatPanel(JSON.parse(e.data)));
}
document.getElementById('setname').style.display = 'none';
}
function createChatPanel(data){
var name = data.name;
var text = data.text;
var div = document.createElement('div');
var p1 = document.createElement('p');
var p2 = document.createElement('p');
p1.innerHTML = name + ":" + (new Date()).toString();
p2.innerHTML = text;
p1.style.color = 'green';
div.appendChild(p1);
div.appendChild(p2);
return div;
}
</script>
</body>
</html>