How to Integrate Nodejs + Socket.Io and PHP

How to integrate nodeJS + Socket.IO and PHP?

So, to begin with, I put my project on github, if you want access to the full code: https://github.com/jdutheil/nodePHP

It is a very simple example project: a web chat. You just have an author and message, and when you press send it is saved in a mysql database. The idea is to send real time updates, and have a real conversation. ;) We'll use nodeJS for that.

I won't talk about PHP code, it is really simple and not interesting here; what I want to show you is how to integrate your nodeJS code.

I use express and Socket.IO, so be sure to install those modules with npm. Then, we create a simple nodeJS server:

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 );

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

server.listen( 8080 );

We registered our events callback when a new user is connected ; every time we receive a message (represents a chat message), we broadcast it to every users connected. Now, the tricky part: client-side! That the part that took me most of the time, because I didn't know which script include to be able to run Socket.IO code without the nodeServer (because client page will be served by Apache).

But everything is already done; when you install Socket.IO module with npm, a script is available in /node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js; that the script we will include in our PHP page, in my case:

    <script src="js/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="js/nodeClient.js"></script>

And to finish, my nodeClient.js, where we simply connect to the node server and wait for event to update our page. ;)

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

$( "#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 );
});

I'll try to update and improve my code as soon as possible, but I think it already open to all of cool things! I am really open for advice and reviews on this stuff, is it the good way to do it, .. ?

Hope this can help some people!

Connect to socket.io(nodejs) via PHP

I also encountered this problem. Learned a lot of structure websocket requests. I wrote a library for yourself, you can use it.PHP SocketIO Client.

You need simple socket connect to nodejs, compose in this message format.42["message", "your message"]' To encode to hybi10 (or hybi13) and send to websocket

Integrating Socket.io with a PHP web app and Nginx

Solved it in the end. First problem was that QUEUE_DRIVER and BROADCAST_DRIVER were both set to redis, which broke the broadcasting system - it used PUSH instead of PUBLISH. I therefore removed QUEUE_DRIVER and the messages were being received correctly.

The chat script needed to use HTTPS and load the SSL certificate:

var fs = require('fs');
var pkey = fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem');
var pcert = fs.readFileSync('/etc/letsencrypt/live/example.com/fullchain.pem')
var options = {
key: pkey,
cert: pcert
};
var app = require('https').createServer(options);
var io = require('socket.io')(app);
var Redis = require('ioredis');
var redis = new Redis();
app.listen(9000, function() {
console.log('Server is running!');
});
function handler(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.writeHead(200);
res.end('');
}
io.on('connection', function(socket) {
//
});
redis.psubscribe('*', function(err, count) {
//
});
redis.on('pmessage', function(subscribed, channel, message) {
message = JSON.parse(message);
console.log('Channel is ' + channel + ' and message is ' + message);
io.emit(channel, message.data);
});

The client-side implementation needed to use the secure parameter:

var url = window.location.protocol + '//' + window.location.hostname;
var socket = io(url, {
'secure': true,
'reconnect': true,
'reconnection delay': 500,
'max reconnection attempts': 10
});
var chosenEvent = 'room_' + room.id;
socket.on(chosenEvent, function (data) {
console.log(data);
});

Once I'd made those changes, it worked fine.

PHP sending message to Node / Socket.IO server

im using http://elephant.io/ for comunication between php and socket.io, i have only problems with the time to stablish connection, 3 or 4 seconds to complete sending data.

<?php

require( __DIR__ . '/ElephantIO/Client.php');
use ElephantIO\Client as ElephantIOClient;

$elephant = new ElephantIOClient('http://localhost:8080', 'socket.io', 1, false, true, true);

$elephant->init();
$elephant->emit('message', 'foo');
$elephant->close();

nodeJS and PHP (Laravel) integration for Socket.IO live chat

the solution is simple (but finding ANYTHING about it on the internet was not). You just need to include your socket.io JS file in the HTML view of PHP, then the socket.io JS files makes a connection to your node.JS server. This works all fine on localhost. However, if someone else tries to log into your chat from outside, they will experience a "Forbidden crossdomain request" error, which is because you have probably followed some "guide" like me and your socket.io connection in the CLIENT is like that:

var socket = io.connect('localhost:8080');

instead of

var baseURL               = getBaseURL(); // Call function to determine it
var socketIOPort = 8080;
var socketIOLocation = baseURL + socketIOPort; // Build Socket.IO location
var socket = io.connect(socketIOLocation);

// Build the user-specific path to the socket.io server, so it works both on 'localhost' and a 'real domain'
function getBaseURL()
{
baseURL = location.protocol + "//" + location.hostname + ":" + location.port;
return baseURL;
}

The PHP client code is:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>

<!-- Wrapper-->
<div id="wrapper">

<!-- Chat: Input -->
<div id="chat-input">

<!-- Username -->
<div class="username">
<p id="username">John Doe</p>
</div>

<!-- Form -->
<form action="">

<!-- Input field -->
<input type="text" class="chat_input-message" id="message" placeholder="Enter your message..." autocomplete="off" autofocus="on" />

<!-- Button -->
<button>Send</button>

</form>
<!-- END: Form -->
</div>
<!-- END Chat: Input -->

<div id="chat-output">
<div id="messages"></div>
</div>

</div>
<!-- END: Wrapper -->

<!-- Scripts -->
<!-- Socket.IO -->
<script src="../node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
<!-- jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Chat -->
<script src="../public/js/chat.js"></script>
<!-- End: Scripts -->

</body>
</html>

The server-side node.JS code does not need any tweaks, forget everything about Redis or in PHP (Elephant.IO, AJAX random injects, forget about any hacks). It simply works as a magic.



Related Topics



Leave a reply



Submit