美文网首页程序员技术文
基于Node.js、socket.io实现websocket聊天

基于Node.js、socket.io实现websocket聊天

作者: Scoor | 来源:发表于2016-10-07 09:22 被阅读0次

    [TOC]

    Node.js与NPM

    使用Socket.io需要安装Node.js与NPM(node package manager),具体安装方式参考链接或网上搜索这里就不再介绍了。

    友情提示:即使不使用Node.js技术,也建议安装,很多开源的三方插件都提供npm下载

    Express

    Express是Node.js轻量级框架,小巧玲珑,安装很方便,cd到node项目下:

    npm install express --save
    

    Socket.io

    Socket.io是对Websocket的简化与补充,使用Socket.io对初学者而言不用过多的了解Websocket的各种特性但能完成一些通信、通知等Websocket所具有的功能。这篇博客是我在第一次使用Socket.io之后的心得,写作目的是为了方便像我一样的新手学习,同样为了将来自己再次使用Socket.io时少走弯路。

    服务端代码

    var express=require('express'),
        app=express(),
        server=require('http').createServer(app),
        io=require('socket.io').listen(server);
    app.get('/', function (req, res) {
        res.send('welcome to chatroom');
    });
    //用户列表{令牌:用户名}
    var user_info={};
    //status状态表{令牌:状态}
    var coding_status={};
    io.on('connection', function(socket){
        //服务器监听message事件
        socket.on('message', function(msg){
            //服务器向[全部客户端]发送message事件
            io.sockets.emit('message', {user:user_info[socket.id],data:msg});
        });
        //服务器监听login事件-->
        socket.on('login', function(name){
            //服务器向[请求客户端]发送login事件
            socket.emit('login',{self:true,data:name});
            //服务器向[其他客户端]发送login事件
            socket.broadcast.emit('login',{self:false,data:name});
            //服务器记录[请求客户端]的令牌与用户名
            user_info[socket.id]=name;
        });
        //服务器监听coding事件-->
        socket.on('coding',function(status){
            if(status!=coding_status[socket.id]){
                //服务器向[其他客户端]发送coding事件
                socket.broadcast.emit('coding',{user:user_info[socket.id],status:status});
            }
            //服务器记录[请求客户端]的令牌与status
            coding_status[socket.id]=status
        })
    });
    server.listen(8080);//服务器监听8080端口 
    

    客户端

    <body>
        <div style="display: flex;flex-direction: column;justify-content: center;align-items:center;width: 100%;">
            <p>Disgusting chat room!!</p>
            <div id="chat-room" style="min-height: 200px;width:400px;border: 1px solid #ccc;">
            </div>
            <div id="coding">
            </div>    
            <div style="width:400px;display:flex;justify-content:space-between;">
                <input id="message" style="width:70%;"/><button id="send_btn">Send Message</button>
            </div>
        </div>
    </body>
    <script src="./node_modules/socket.io/socket.io.js"></script>
    <script src="./node_modules/jquery/jquery.min.js"></script>
    <script>
    var socket = io.connect('http://192.168.1.96:8080');
    $('#message').on('focus',function(){
        if($('#message').val()!=""){
            socket.emit('coding',1);
        }
        return false;
    });
    $('#message').on('keyup',function(){
        if($('#message').val()!=""){
            socket.emit('coding',1);
        }else{
            socket.emit('coding',0);
        }
    });
    $('#message').on('blur',function(){
        socket.emit('coding',0);
    });
    $('#send_btn').on('click',function(){
        if($('#message').val()==""){
            return;
        }
        socket.emit('message', $('#message').val());
        $('#message').val("")
        return false;
    });
    //监听message事件
    socket.on('message', function(obj){
        $("#chat-room").append("<p><span style='color:red'>"+obj.user+":</span>"+obj.data+"</p>");
    });
    //监听login事件
    socket.on('login', function(obj){
        if(obj.self==true){
            $("#chat-room").append("<p><span style='color:red'>Welcome!</span>"+obj.data+"</p>");
        }
        if(obj.self==false){
            $("#chat-room").append("<p><span style='color:red'>"+obj.data+"</span> have joined room!</p>");
        }
    });
    //监听status事件
    socket.on('coding', function(obj){
        if(obj.status==1){
            $("#coding").append("<p id='"+obj.user+"'><span style='color:red'>"+obj.user+"</span> is coding</p>");
        }
        if(obj.status==0){
            $("#"+obj.user+"").remove();
        }
    });
    var time=new Date()
    var name=prompt("Please enter your name!","test"+time.getHours()+time.getSeconds())
    if (name!=null && name!=""){
        socket.emit('login',name);
        // socket.broadcast.emit('');
    }
    </script>
    

    Socket.io内置事件

    • connect:连接成功
    • connecting:正在连接
    • disconnect:断开连接
    • connect_failed:连接失败
    • error:错误发生,并且无法被其他事件类型所处理
    • message:同服务器端message事件
    • anything:同服务器端anything事件
    • reconnect_failed:重连失败
    • reconnect:成功重连
    • reconnecting:正在重连

    上面是socket.io内置事件,除了内置事件,我们还可以自定事件,比如代码中的coding就是我们自定义的事件。

    Socket.io事件请求与监听

    服务器端数据传输

    socket.emit(event, data);//向[请求客户端]发送事件
    socket.broadcast.emit(event, data);//向[其他客户端]发送事件
    io.sockets.emit(event, data);//向[所有客户端]发送事件
    io.sockets.socket(socketid).emit(event,data);//向[指定客户端]发送事件
    

    请求客户端:sender
    其他客户端 :all connected clients expect sender
    所有客户端:all connected clients

    socket.on(event,function(data){})//事件监听
    类似于jquery语法,data是触发事件时携带的数据

    运行结果

    运行结果

    介绍了些socket.io的基础功能,希望对大家有用,抛砖引玉
    git项目地址:Scorcjw/SocketDemo

    相关文章

      网友评论

        本文标题:基于Node.js、socket.io实现websocket聊天

        本文链接:https://www.haomeiwen.com/subject/hxveyttx.html