WebSocket学习(四)——使用WebSocket实现聊天室

前面说了用nodejs搭建WebSocket服务器,实现了前后台的数据交换,然后就可以想到我们用WebSocket实现一个简单的聊天室

1、先搭建一个服务器吧(nodejs实现),z直接上代码了

wsServer.js

// 引入WebSocket模块
var ws = require('nodejs-websocket')

var PORT = 3000
var clientCount = 0

var server = ws.createServer(function(conn){
    console.log('New connection')
    
    // 给每个用户取名字
    clientCount++
    conn.nickname = 'user' + clientCount

    // 将消息写成一个对象,传到前台是一个消息对象而不只是消息本身
    var mes = {}
    mes.type = "enter"
    mes.data = conn.nickname + 'come in'
    // JSON.stringify()把对象转化为一个字符串发送到前台

    // 通知用户上线
    broadcast(JSON.stringify(mes))

    // 收到客户端消息
    conn.on("text",function(str){
        console.log("Received"+str)
        // conn.sendText(str.toUpperCase()+"!!!") //大写收到的数据
        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("handle err")
        console.log(err)
    })
}).listen(PORT)

console.log('websocket server listening on port ' + PORT)

// 广播消息
function broadcast(str){
    // server.connections取到所有的连接,循环发送给所有人
    server.connections.forEach(function(connection){
        connection.sendText(str)
    })
}

就是有几点要注意:1、把消息弄成了一个对象(我们要知道消息的类型Type如上线下线普通消息,要知道消息的数据)

2、因为消息是一个对象,所以发送时要用JSON.stringify(mes)把消息转化为一个字符串才能发送

3、聊天室是个群聊,所以有个广播消息的函数,遍历连接一个个发送

2、然后前台代码

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">
    <title>WebSocket</title>
</head>
<body>
    <h1>Chat Room</h1>
    <input id="sendTxt" type="text"/>
    <button id="sendBtn">发送</button>
    <div id="recv"></div>
    <script type="text/javascript">
        // //官方示例的服务器
        // var WebSocket = new WebSocket("ws://echo.websocket.org");
        // wsServer搭建的服务器
        var WebSocket = new WebSocket("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)
        }

        // 连接到服务器后
        WebSocket.onopen = function(){
            console.log('websocket 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>
和上篇文章一样,只不过接收了消息的类型,因此写了个showMessage(str,type)方法对不同的消息显示时间不同

运行注意要先node wsSocket启动服务器,然后打开几个html页面就可以看效果了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值