简体   繁体   中英

Integrating node.js, socket.io and php web page

I am going to integrate my php web page with node.js and socket.io. The client can connect to node.js server file but the socket.emit function does not work from client to the server or return. Here is my nodeClient.js file:

var socket = io.connect( 'http://192.168.0.10:8080/index3.php' );

$( "#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( 'new message', function( data ) {
    var actualContent = $( "#messages" ).html();
    var newMsgContent = '<li> <strong>' + data.name + '</strong> : ' + data.message + '</li>';
    var content = newMsgContent + actualContent;

    $( "#messages" ).append(newMsgContent);
});

here is the nodeServer.js file:

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( 'new message', { name: data.name, message: data.message } );
});
});

server.listen( 8080, function(){
  console.log('listening on *:8080');
});

the ajax works to store the data in mysql. Each client connected is recognized "New Client!". But no message communicating between client and server. What could be the problem in my code.

correct your JSON syntax instead of writing on client side:

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

write

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

same on server side you actually missed the double quotes while writing the name of value in json object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM