websocket实现简单聊天功能之四
页面展示效果如下:
具体实现代码:
先启动websocket的服务:
项目目录结构:
服务端js:
var ws=require("nodejs-websocket")
//定义端口号
var port=8003;
var clientCount=0;
var server=ws.createServer(function (conn) {
console.log("new connction");
clientCount++;
conn.nickname="user"+clientCount;
//创建一个对象
var mes={};
mes.type="enter";
mes.data=conn.nickname+'comes in';
broadcast(JSON.stringify(mes));
conn.on("text",function (str) {
console.log("received "+str);
var mes={};
mes.type="message";
mes.data=conn.nickname+' says:'+str;
broadcast(JSON.stringify(mes));
})
conn.on("close",function (code,reason) {
console.log("connection closed")
var mes={};
mes.type="leave";
mes.data=conn.nickname+' left';
broadcast(JSON.stringify(mes));
})
conn.on("error",function(err){
console.log("handler err")
console.log(err)
})
}).listen(port)
//server启动的时候打印
console.log("websocket3 server listening on port"+port)
//实现广播的方法
function broadcast(str){
server.connections.forEach(function(connection){
connection.sendText(str);
})
}
页面显示:
<html>
<head>
<title>websocket</title>
</head>
<body>
<h1>Chart Room</h1>
<input id="sendTxt" type="text"/>
<button id="sendBtn">发送</button>
<script type="text/javascript">
var websocket=new WebSocket("ws://localhost:8003");
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);
}
//调用回调函数
websocket.onopen=function(){
console.log('wbesocket open');
document.getElementById("sendBtn").onclick=function(){
var txt=document.getElementById("sendTxt").value;
if(txt){
websocket.send(txt);
}
}
}
websocket.onclose=function () {
console.log('websocket close');
}
websocket.onmessage=function (e) {
console.log(e.data);
var mes=JSON.parse(e.data);
showMessage(mes.data,mes.type);
}
</script>
</body>
</html>