如何在welcome.php页面上运行nodejs chat而不是index.php页面

时间:2017-07-16 20:15:45

标签: javascript php node.js

我有一个nodejs聊天,它的工作正常。我从命令提示符运行服务器代码,然后打开浏览器,然后从index.php或index.html页面运行它。

现在我想从另一个页面运行它,例如welcome.php,但它不起作用。在chat.js文件中,我已更改此

var socket = io.connect( 'http://'+window.location.hostname+':3000' );

var socket = io.connect( 'http://localhost/chat/welcome.php' );

但它不起作用

下面的

Chat.js file

的示例
$(function(){
    var socket = io.connect( 'http://'+window.location.hostname+':3000' );
var name = $('#username').val();
var user = $('#user').val();
    socket.on('users', function(data){
        $('.names-list').text('');
        $.each(data,function(i,v){
            $('.names-list').append('<li>'+v+'</li>');
        });
    });

    socket.on('push message', function(response){


        $('.messages').append('<li><div class="msg-lhs"><span class="username"><b style="color:' + response.colorClass + '">'+response.name+'</b></span> : <span class="msg">'+response.msg+'</span></div><span data-livestamp="'+moment().unix()+'" class="msg-rhs"></span></li>');
        $('.messages').animate({scrollTop: $('.messages').prop("scrollHeight")}, 500);
    });

    $(document).on('keyup','.message-box',function(e){
        var $this = $(this);
        if(e.which === 13){

            var message = $this.val();



            socket.emit('new message', message);
            $this.val('');

        }
    });


});
下面的

server.js

的示例
var socket  = require( './node_modules/socket.io' );
var express = require('./node_modules/express');
var app     = express();
var server  = require('http').createServer(app);
var io      = socket.listen( server );
var port    = process.env.PORT || 3000;
var users = [];

server.listen(port, function () {
  console.log('Server listening on port %d', port);
});

io.on('connection', function (socket) {
    socket.on('new user', function(name, callback){
        if(name.length > 0){
            if(users.indexOf(name) == -1){
                socket.username = name;
                users.push(socket.username);
                updateUsers();
                callback(true);
            } else{
                callback(false);
            }
        }
    });

    socket.on('new message', function(msg){
        var sender = socket.username;
        var message = msg;
        io.emit('push message', {name: sender, msg: message});
    });

    function updateUsers(){
        io.emit('users', users);
    }

    socket.on('disconnect',function(){
        if(socket.username){
            users.splice(users.indexOf(socket.username),1);
            updateUsers();
        }
    });
});

0 个答案:

没有答案