Let's build a simple websocket Client and Server and have them send messages to one another
Websockets are a fundamental part of the modern internet. We use them more often that we think, and though they may seem scary and daunting (and they are), Vortex aims to provide a simple way to build websocket applications.
Server
Let's start by building a simple server that broadcasts a message to any connected client every 5 seconds.
To create our server, we import our Server type from the websockets module.
We then instantiate the Server object.
Because we want this server to perform actions, we need to have it listening in a separate thread so that the main thread can be free to do work. And so we import Future from the future module.
The Future type wraps a function and executes it in another thread. So we wrap the server's listen call in a Future and it begins listening on port 9002 in a separate thread, leaving the main thread unblocked.
Notice that we have it listening in a while loop. This is so that if we decide to set the variable listening to false, the while loop in the other thread will exit and the thread will terminate.
On the main thread, we have another while loop where we sleep for 5 seconds and then broadcast a simple message. This message gets broadcast to all connected clients.
And that's all it takes to set up a working websocket server!
PEM Files
It's important to note that for the server to work, you will need to include dh.pem and server.pem files in the same directory as your server.vtx file.
These are examples of the files, however you should generate your own:
We import the Client type and instantiate it with the server path we want to connect to.
We set the client's on_message callback to print to the console whenever it receives a message from the server.
Instead of launching the client in another thread, we simply run it in the main thread. That's because all we want this simple client to do is echo the message it receives. That is already handled by the callback, and so the main thread doesn't need to do any further work.
Now we run the server: vortex sockets/server/server.vtx
And then the client: vortex sockets/client/client.vtx
Every 5 seconds you should see the message being printed to the console.
And that's it! You've now built your very own websocket application. Use it as a basis for more complex server/client interactions. To see what else you can do with sockets, refer to the standard modules reference.