Socket = io php example

In your PHP projects, you may need to display some parts of your code according to real time. In such circumstances, by using PHP with socket.io, you can handle this situation

Topic List

  • Setting up node.js on Centos server
  • Setting Socket.io
  • Socket.io Settings
  • Listening socket on client side
  • Sending data from PHP to socket

1-Setting up node.js on Centos server

To do this you just need to run this commands

yum install -y gcc-c++ make curl -sL https://rpm.nodesource.com/setup_10.x | sudo -E bash -
yum install nodejs

To check the setting up is right, look at the version of npm and node.js

node -v
npm -v

2-Setting Socket.io

We will set the socket.io with the ngm that package manager of node.js . To generate package.json file let run this command

npm init -y

Now we can set the Socket.io

npm install --save socket.io

3-Socket.io Settings

Here is the settings for socket.io . Let's create app.js file and let's write this codes inside

// we are installing nodejs http server
const server = require('http').createServer();
const io = require('socket.io')(server);

// this works when connected to the socket
io.on('connection', function(socket){
    
    console.log('connecting..');

    // we are listening to the new-post event, we will send data from the backend here
    socket.on('new-post', function(data){
        
        // If there is data, we send it to the client.
        io.emit('posts', data);
        
    });

    // This works when the socket connection ends
    socket.on('disconnect', function(){
        console.log('someone came and went');
    });
    
});

// we listen on port 5000
server.listen(5000);

We listen with on, we sent with emit to client. Now launch the server with nodejs. But let's do this with pm2 package. So we dont have to reboot the program, let working in the background, Firstly let set the pm2 package.

npm install pm2 -g
pm2 start app.js

Now we can listen the socket as  http://IP_ADRES:5000. If there is nothing shows up when you enter it is normal, because it just requires socket connection. To be sure everything is working correct you can check the http://IP_ADRES:5000/socket.io/socket.io.js file.

4-Listening socket on client side

This part is the easiest part, First of all we need to include the js library of socket.io to page.

Then we connect the our socket address.

var socket = io('http://IP_ADRESI:5000');

// we are listening to the posts event on the socket, if it comes, we will print it and look at the console.
socket.on('posts', function (data) {
    console.log(data);
});

//If we wanted to send more to the socket's posts event by the client, we would still use emit.
socket.emit('posts', {
    'id': 5,
    'title': 'phpExample.Net',
    'content': 'this is test',
    'date': '2021-03-01 20:00:00'
});

If you are using SSL, then you can open a safe socket connection in this way.

var socket = io('https://IP_ADRESI:5000', {
    secure: true
})

5-Sending data from PHP to socket

To do this we are going to use a package name of elephant.io . To set the package on our project

composer require wisembly/elephant.io

When we send a data to socket we use in this way

initialize();
$client->emit('new-post', [
    'title' => 'phpExample.Net',
    'content' => 'test',
    'date' => date('Y-m-d'),
    'id' => 2
]);
$client->close();

This is the situation what we are dealing with. See you :)

I know the struggle man! But I recently had it pretty much working with Workerman. If you have not stumbled upon this php framework then you better check this out!

Well, Workerman is an asynchronous event driven PHP framework for easily building fast, scalable network applications. (I just copied and pasted that from their website hahahah http://www.workerman.net/en/)

The easy way to explain this is that when it comes web socket programming all you really need to have is to have 2 files in your server or local server (wherever you are working at).

  1. server.php (source code which will respond to all the client's request)

  2. client.php/client.html (source code which will do the requesting stuffs)

So basically, you right the code first on you server.php and start the server. Normally, as I am using windows which adds more of the struggle, I run the server through this command --> php server.php start

Well if you are using xampp. Here's one way to do it. Go to wherever you want to put your files. In our case, we're going to the put the files in

C:/xampp/htdocs/websocket/server.php

C:/xampp/htdocs/websocket/client.php or client.html

Assuming that you already have those files in your local server. Open your Git Bash or Command Line or Terminal or whichever you are using and download the php libraries here.

https://github.com/walkor/Workerman

https://github.com/walkor/phpsocket.io

I usually download it via composer and just autoload those files in my php scripts.

And also check this one. This is really important! You need this javascript libary in order for you client.php or client.html to communicate with the server.php when you run it.

https://github.com/walkor/phpsocket.io/tree/master/examples/chat/public/socket.io-client

I just copy and pasted that socket.io-client folder on the same level as my server.php and my client.php

Here is the server.php sourcecode

on('connection', function($socket)use($io){
    $socket->on('send message', function($msg)use($io){
        $io->emit('new message', $msg);
    });
});

Worker::runAll();

And here is the client.php or client.html sourcecode



    
        Chat
        
                
    
    
        

Once again, open your command line or git bash or terminal where you put your server.php file. So in our case, that is C:/xampp/htdocs/websocket/ and typed in php server.php start and press enter.

Then go to you browser and type http://localhost/websocket/client.php to visit your site. Then just type anything to that textbox and you will see a basic php websocket on the go!

You just need to remember. In web socket programming, it just needs a server and a client. Run the server code first and the open the client code. And there you have it! Hope this helps!

Can we use Socket.IO with PHP?

If you want to use socket.io together with php this may be your answer! Elephant.io provides a socket.io client fully written in PHP that should be usable everywhere in your project.

How do I connect Socket.IO to HTML?

The script section in index.html should now look as follows:.
.