In this post I would like to present a small tutorial, I hope it will serve as a good introduction to web-socket api.
Websocket Server
In the part we focus on server part. In ruby we use eventmachine, em-websocket gem to install websocket server.
To install eventmachine run gem install eventmachine
To install em-websocket run gem install em-websocket
Make a file server.rb and implement codes below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
What the code does is creates a websocket-server which listens at localhost:8080. Callbacks have been provided for open and close events, so when a client creates a connection or a connection gets closed the associated callbacks print an appropriate message to the terminal. And callbacks have been provided for message event when a client send the message.
To run websocket server run ruby sever.rb
Websocket Client
So far, so good. But the main purpose of a websocket server is to get the message from client and relay data to the client. How do we do that? Turns out that is pretty simple too.
Make a file index.html and implement codes below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
Feel free to provide your suggestions and to point out errors.