node与socket.io搭配小例子-转载

Posted 一根PHP

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了node与socket.io搭配小例子-转载相关的知识,希望对你有一定的参考价值。

//服务端代码
io = require(‘socket.io‘).listen(app), 
fs = require(‘fs‘),
cookie=require(‘cookie‘);
request=require(‘request‘);
global.userlist={};
 
app.listen(8080);
//io.set(‘log level‘, 1);//将socket.io中的debug信息关闭
 
function handler (req, res) {
    res.writeHead(200, {
        ‘Content-Type‘: ‘text/plain‘
    });
    res.end(‘Hello World\n‘);
}
var content;
var socketUser = {};
var settings={};
settings.host=‘http://localhost/test/node/myapp/‘;
io.sockets.on(‘connection‘, function (socket) {
    if(socket.handshake.headers.cookie){
        var curcookie=cookie.parse(socket.handshake.headers.cookie);
        var id=curcookie[‘phpSESSID‘];
        request(settings.host+‘getinfo.php?type=getinfo&sid=‘+id,function(err,res,body){
            if(!err&&res.statusCode==200){
                if(body){
                    body=eval(‘(‘+body+‘)‘);
                    var userid=body.ID;
                    var username=body.UserName;
                    var online=body.Online;
                    //将新用户存进socket用户列表中
                    userlist[id]=socket;
                 
                    socketUser[id] = {
                        ‘userid‘:userid,
                        ‘username‘:username
                    };
                    //更改上线状态
                    request(settings.host+‘getinfo.php?type=online&sid=‘+id,function(err,res,body){})
         
                    //发送信息给新登录用户
                    socket.emit(‘system‘,{
                        ‘alluser‘:socketUser
                    });
         
                    //上线欢迎
                    socket.emit(‘open‘,{
                        ‘msg‘:‘welcome!‘
                    })
         
                    //下线推送通知  disconnect方法名不能修改
                    socket.on(‘disconnect‘,function(){
                        //更改用户不在线
                        socketUser[id]=null;
                        userlist[id]=null;
                        request(settings.host+‘getinfo.php?type=unline&sid=‘+id,function(err,res,body){})
                        socket.broadcast.emit(‘broadcast‘,{
                            ‘msg‘:‘noline‘,
                            ‘unlineid‘:userid,
                            ‘unlinename‘:username,
                            ‘type‘:1
                        });
                    })
         
                    //监听接收用户信息
                    socket.on(‘sendnews‘, function (data) {
                        if(data.touserid&&userlist[data.touserid]!=undefined){
                            var user=userlist[data.touserid];
                            data.fromusername=socketUser[data.fromuserid].username;
                            //将用户信息发送给指定用户
                            user.emit(‘receivenews‘,data);
                        }else{
                            socket.emit(‘receivenews‘,data);
                        }
                    });
     
                    //广播  推送已登录的用户
                    socket.broadcast.emit(‘broadcast‘,{
                        ‘userid‘:userid,
                        ‘username‘:username,
                        ‘type‘:2
                    });
                }else{
                    console.log(‘falseness connect‘); 
                }            
            }
        })      
    }else{
        console.log(‘cookie not exist‘);
    }
});
//客户端代码

<?php
$data = $_GET;
if (!isset($data[‘username‘]) || $data[‘username‘] === ‘‘ || !isset($data[‘id‘]) || $data[‘id‘] === ‘‘) {
    header("location:login.php");
}
session_id($data[‘id‘]);
session_start();
$userid = $data[‘id‘];
$name = $data[‘username‘];
$con = <a href="https://www.baidu.com/s?wd=mysql_connect&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YvPAndmhNWnWu9nvczmWb10ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EnHT1n1D4P1R4PjnkPjcdnW6vPs" target="_blank" class="baidu-highlight">mysql_connect</a>("localhost", "root", "") or die("sds");
<a href="https://www.baidu.com/s?wd=mysql_select_db&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YvPAndmhNWnWu9nvczmWb10ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EnHT1n1D4P1R4PjnkPjcdnW6vPs" target="_blank" class="baidu-highlight">mysql_select_db</a>("test", $con);
mysql_query("set names utf8");
$sql = ‘select * from io_user where username="‘ . $name . ‘" and ID=‘ . $userid;
$result = mysql_query($sql);
$res = mysql_fetch_assoc($result);
if (!$res) {
    header("location:login.php");
}
?>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Ssocket</title>
        <script type="text/javascript" src="public/javascripts/jquery.min.js"></script>   
        <script type="text/javascript" src="http://localhost:8080/socket.io/socket.io.js"></script>   
    </head>
 
    <body>
        <p>我的id:<?php echo $userid ?></p>
        <p>我的名字:<?php echo $name; ?></p>
        <h4>在线用户列表</h4>
        <table border="1" id="userlists">
            <thead>
                <tr>
                    <th width="80px">ID</th>
                    <th width="80px">用户名</th>
                    <th width="80px">选中</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        <p style="margin-top:10px">
            信息:
            <input type="text" style="width:338px" id="content">
            <button id="send">发送</button>
        </p>
        <div id="msg"></div>
        <div id="unline"></div>
        <script type="text/javascript">
            var userid=‘<?php echo $userid; ?>‘;
            var username=‘<?php echo $name; ?>‘;
            var socket = io.connect(‘http://localhost:8080‘);
             
            //欢迎信息
            socket.on(‘open‘,function(res){
                console.log(res);
            })
             
            //无连接
            socket.on(‘disconnect‘,function(res){
                console.log(‘not connect‘);
            })
             
            //接收用户消息
            socket.on(‘receivenews‘,function(res){
                var html=‘<p>来自用户 (‘+res.fromusername+‘) 的消息: ‘+res.content+‘</p>‘;
                $(‘#msg‘).append(html)
            })
             
            //接收系统消息
            socket.on(‘system‘,function(res){  
                if(res.alluser){
                    var html=‘‘;
                    var time=0;
                    $.each(res.alluser,function(k,v){
                        if(v==null||v.userid==userid){
                            return;
                        }
                        time++;
                        html+=‘<tr userid="‘+v.userid+‘"><td>‘+time+‘<td>‘+v.username+‘</td>‘;
                        html+=‘<td><input type="checkbox" class="checkbox" userid="‘+v.userid+‘"></td></tr>‘;  
                         
                    })
                    $(‘#userlists tbody‘).html(html);                   
                }
            })
             
            //获取推送信息
            socket.on(‘broadcast‘,function(res){ 
                if(res.type==1&&res.unlineid!=userid){
                    $(‘#userlists tbody tr[userid="‘+res.unlineid+‘"]‘).remove();
                    $(‘#unline‘).append(‘<p>用户‘+res.unlinename+‘离线</p>‘)
                    return false;
                }
                if(res.type==2&&res.userid){
                    if(res.userid==userid){
                        return false;
                    }
                    if($(‘#userlists tbody tr[userid="‘+res.userid+‘"]‘).length>0){
                        return false;
                    }
                    var html=‘‘;
                    var length=$(‘#userlists tbody tr‘).length;
                    html+=‘<tr userid="‘+res.userid+‘"><td>‘+(length+1)+‘<td>‘+res.username+‘</td>‘;
                    html+=‘<td><input type="checkbox" class="checkbox" userid="‘+res.userid+‘"></td></tr>‘; 
                    $(‘#userlists tbody‘).append(html);    
                    $(‘#unline‘).append(‘<p>用户‘+res.username+‘上线</p>‘)
                    return false;
                }
            })
             
            $(function(){
                $(‘.checkbox‘).live(‘click‘,function(){
                    if($(this).attr(‘checked‘)==‘checked‘){
                        $(‘.checkbox‘).removeAttr(‘checked‘);
                        $(this).attr(‘checked‘,true);
                    }
                     
                })
                 
                //输入框回车事件
                $("#content").keyup(function(e){
                    if(e.keyCode==13){
                        $(‘#send‘).trigger(‘click‘);
                    }
                    return false;
                });
                 
                $(‘#send‘).click(function(){
                    var content=$(‘#content‘).val();
                    var data={};
                    var touserid=$(‘.checkbox[checked]‘).attr(‘userid‘);
                    if(touserid==undefined){
                        alert(‘请选择用户‘);
                        return false;
                    }
                    if(content!=‘‘){
                        $(‘#content‘).val(‘‘);
                        data.fromuserid=userid;
                        data.touserid=touserid;
                        data.content=content;
                        //发送信息
                        socket.emit(‘sendnews‘,data);
                    }
                })
            })
        </script>
    </body>
</html>

代码网上转载而来,质量不论,仅做参考

以上是关于node与socket.io搭配小例子-转载的主要内容,如果未能解决你的问题,请参考以下文章

使用Node.js+Socket.IO搭建WebSocket实时应用转载

使用 node.js、socket.io 和 redis 的一对一聊天应用程序

后端使用 Swift 和 Node.js 的 Socket.io 示例

Heroku 上的 Socket.io 聊天应用程序与 node.js

Node.js socket.io 没有响应 iOS socket.io 发出请求

如何将 Asterisk ARI 与 socket.io 和 Node.js 一起使用