JuliaWeb / WebSockets.jl

A WebSockets library for Julia
MIT License
157 stars 58 forks source link

Example in the Getting Started fails. #173

Closed shrimpceviche closed 1 year ago

shrimpceviche commented 3 years ago

I tried the example, and did not get WebSocket(client, CONNECTED) received:Hello. The reason is that the server only sends out "Hello" when it starts, and the client portion of the code is not compiled quickly enough to recieve the "Hello". I wrote the following example ( quality can be improved ), please feel modify and post. Thank you.

using WebSockets
import WebSockets:Response,
                  Request
using Dates
using Sockets

const HTTPPORT = 8000
const LOCALIP = string(Sockets.getipaddr())

function coroutine(thisws)
    while true
        writeguarded(thisws, "hello")
        sleep(3)
    end
    nothing
end

function gatekeeper(req, ws)
    orig = WebSockets.origin(req)
    if occursin(LOCALIP, orig) | occursin("", orig)
        coroutine(ws)
    else        
        @warn("Unauthorized websocket connection, $orig not approved by gatekeeper, expected $LOCALIP")
    end
    nothing
end

serverWS = WebSockets.ServerWS((req) -> WebSockets.Response(200), 
                                        gatekeeper)
@async begin 
    try
        WebSockets.with_logger(WebSocketLogger()) do
            WebSockets.serve(serverWS, port=HTTPPORT)
        end

    catch exc 
        println(stacktrace())
        println(exc)
    end
end

WebSockets.HTTP.get("http://127.0.0.1:8000")

client_task = @async begin
    try
        WebSockets.open("ws://127.0.0.1:8000") do ws_client

            while !eof(ws_client)
                data, success = readguarded(ws_client)

                if success
                    println(" received:", String(data), " at $(now())")
                else
                    println("read ws failed.")
                end
            end
        end;
    catch exc
        println(stacktrace())
        println(exc)
    end
end;
hustf commented 1 year ago

WebSockets.jl now has a new version, requiring Julia 1.8.2+ and HTTP 1.1.0 to 1.5. Hopefully, this solves the issue; simply do Pkg.update(), and see the updated README!