duanbi5906
duanbi5906
2015-01-24 10:54

SocketIO Nodejs和PHP,如何使其工作?

I have this simple chat app, that is supposed to show received messages in real time without refreshing.

I am running xampp on port 80.

This I have included on index.php

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
    <script src="js/bootstrap.js"></script>
    <script src="http://localhost:80/nodePHP-master\js
ode_modules\socket.io
ode_modules\socket.io-client/socket.io.js"></script>
    <script src="js/nodeClient.js"></script>

nodeClient.js is

    var socket = io.connect( 'http://localhost:80' );

    $( "#messageForm" ).submit( function() {
    var nameVal = $( "#nameInput" ).val();
    var msg = $( "#messageInput" ).val();

    socket.emit( 'message', { name: nameVal, message: msg } );

    // Ajax call for saving datas
    $.ajax({
    url: "./ajax/insertNewMessage.php",
    type: "POST",
    data: { name: nameVal, message: msg },
    success: function(data) {

    }
    });

    return false;
     });

    socket.on( 'message', function( data ) {
    var actualContent = $( "#messages" ).html();
    var newMsgContent = '<li> <strong>' + data.name + '</strong> : ' +        data.message + '</li>';
   var content = newMsgContent + actualContent;

   $( "#messages" ).html( content );
   });

And nodeServer.js is

    var socket = require( 'socket.io' );
    var express = require( 'express' );
    var http = require( 'http' );

    var app = express();
    var server = http.createServer( app );

    var io = socket.listen( server );

    io.sockets.on( 'connection', function( client ) {
    console.log( "New client !" );

    client.on( 'message', function( data ) {
    console.log( 'Message received ' + data.name + ":" + data.message );

    //client.broadcast.emit( 'message', { name: data.name, message:  data.message } );
    io.sockets.emit( 'message', { name: data.name, message: data.message }   );
    });
    });

    server.listen( 80 ); 

But I keep getting this error message in console :

enter image description here

What am I doing wrong ?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongmei6426 dongmei6426 6年前

    I've solved it.

    Did not know that I had to start nodeServer.js

    Accessed its location via cmd, and endered node nodeServer.js

    点赞 评论 复制链接分享