Reputation: 27225
I'm messing around with WebSockets and I have written an "echo server" which I expected to log to the console as it runs:
echo = Warp.run 3000 app
where
app = WS.websocketsOr
WS.defaultConnectionOptions
wsApp
httpApp
httpApp _ respond = do
put "HTTP Request Recieved"
respond $ Wai.responseFile
Http.status200
[]
"web/index.html"
Nothing
wsApp :: WS.ServerApp
wsApp pendingConn = do
conn <- WS.acceptRequest pendingConn
WS.forkPingThread conn 30
put "WebSocket Connection Open"
listen conn
listen :: WS.Connection -> IO ()
listen conn = forever $ do
str <- WS.receiveData conn :: (IO Text.Text)
put $ Text.unpack str
WS.sendTextData conn str
main :: IO ()
main = do
put "Echo WebSocket Running ..."
echo
put str = hPutStrLn stdout str >> hFlush stdout
As you can see, I've tried flushing stdout
but with no success. I get
$ ./echoServer
Echo WebSocket Running ...
but nothing more. Even though I can successfully load "web/index.html" in a browser and successfully establish a connection to the WebSocket and use it, I get no feedback from the console.
What do I need to do to get output to the console?
Library Versions:
Upvotes: 2
Views: 139
Reputation: 27225
The above code actually works, but not when nothing happens! This question was the result of a nasty cache invalidation error, and not an error in my code.
I wrote the client side first (using Elm, highly recommended) and hard coded the websocket to point to wss://echo.websocket.org
so I could test the front end. I then got the backend to serve me the file that Elm had created (but still pointed at wss://echo.websocket.org
). Realizing my mistake, I changed the elm script to point at localhost and added some logging to the back-end as seen above.
I then restarted the server and pointed my browser at localhost:3000. The browser loaded up the cached copy (no HTTP request) which still pointed at wss://echo.websocket.org
(no websocket request).
It looked like the front end was working, but the backend was not logging. In point of fact there were no requests coming into the back end at all.
I came back this evening and started messing with my code to see if I could get everything to work and the first time I ran the server everything (almost) worked, but I had not made any effective changes, just added some new 'include' lines. The cache had expired. The big tip was that everything but the HTTP request logged correctly. "Now why would that one request be different?" I asked myself. Then it hit me that there was caching going on and that a stale cache could account for everything I was seeing this morning.
Other than feeling a bit humiliated at not recognizing this earlier, everything is working now.
There are only two hard things in Computer Science: cache invalidation and naming things. -- Phil Karlton
Upvotes: 2