This is a server-side implementation of the WebSockets protocol in Julia. If you want to write a web app in Julia that uses WebSockets, you'll need this package.
This package works with HttpServer.jl, which is what you use to set up a server that accepts HTTP(S) connections.
As a first example, we can create a WebSockets echo server:
using HttpServer
using WebSockets
wsh = WebSocketHandler() do req,client
while true
msg = read(client)
write(client, msg)
end
end
server = Server(wsh)
run(server,8080)
This sets up a server running on localhost, port 8080.
It will accept WebSockets connections.
The function in wsh
will be called once per connection; it takes over that connection.
In this case, it reads each msg
from the client
and then writes the same message back: a basic echo server.
The function that you pass to the WebSocketHandler
constructor takes two arguments:
a Request
from HttpCommon.jl,
and a WebSocket
from here.
You can:
write
data to itread
data from it- send
ping
orpong
messages close
the connection
julia> Pkg.add("WebSockets")
At this point, you can use the examples below to test that it all works.
- Move to the
~/.julia/<version>/WebSockets
directory - Run
julia examples/chat.jl
- In a web browser, open
localhost:8000
- You should see a basic IRC-like chat application
using HttpServer
using WebSockets
wsh = WebSocketHandler() do req,client
while true
msg = read(client)
write(client, msg)
end
end
server = Server(wsh)
run(server,8080)
To play with a WebSockets echo server, you can:
- Paste the above code in to the Julia REPL
- Open
localhost:8080
in Chrome - Open the Chrome developers tools console
- Type
ws = new WebSocket("ws://localhost:8080");
into the console - Type
ws.send("hi")
into the console. - Switch to the 'Network' tab; click on the request; click on the 'frames' tab.
- You will see the two frames containing "hi": one sent and one received.
::::::::::::::::
:: ::
:: Made at ::
:: ::
::::::::::::::::
::
Recurse Center
::::::::::::::::