Recently I did a post about HTML5 WebSockets and it had a purpose. I was preparing the material of my talk at Samsung Ocean and my goal was create a RC car with an Hybrid application to control it and not use java as a server-side language.
The final result you can check on my github and play around with the code.
The following steps are to getting the socket working in your raspberry, here I'm going to use the model B+.
First of all
We need to to access our Pi trough the SSH, for this example I'm going to use the WiPi (wireless adapter for raspberry Pi)
But you can use the RJ-45 to access it or use a little monitor with a keyboard on the Pi, fell free to choose your option just make sure you will have this access.
For this example we are going to use only the php without any web server, it is interesting isn't it ? Let's update our Pi and install the php
After a few minutes the pi will be up to date and then we can finally install PHP
Setting up the socket
Choose a directory and create a socket.php file with the content below, I'm going to use my own directory called /home/marabesi
Now we have to create a simple HTML file to interact with our socket and see it working, from now on we have two path to take the first is to create an HTML file on the Pi and then access it, and the second is to create a simple HTML in our own PC and just make the connection to our socket into the Pi.
Just make sure you execute the socket.php file in the Pi to be able to listen on port 9000
If everything goes well you'll see the following message
IMPORTANT : You must keep the socket.php executing otherwise it won't let you connect through the socket.
To simplify this post I'm going to go with the second option, but you can install a web server such as nginx in your pi and try it yourself!
As a alternative you can use the Ratchet to create you socket in a much easier way and with a amazing use of Object Oriented Programming you should check it out.
Creating the HTML page to interact with
Now we can save the following code in a file called index.html
Here we have to modify two thing to get the things done.
1) Where you see raspberryIp you should change to you raspberry IP
2) And where you see raspberryPort you should also change to the port where the socket is running and in this example the port is 9002
The HTML code was originally made on codepen.io and you can see the working example above, with the bootstrap style.
Suggestions ? please let me know!
Edit: 17/03/2016 - Setting up Apache virtual host
If you don't have apache installed just type
You can install it on raspberry pi or anywhere you want to.
After that we need create a virtual host.
and with the file created just copy and paste the following code
As you can see our root directory is /var/www/websocket and is the place where you should save the HTML we created to manipulate our socket connection.