# The WebSocket demo: front and back in one file. # The browser opens the page using a usual request, then the JS opens it using ws://. @main[] ^if($env:HTTP_UPGRADE eq websocket){ ^back[] }{ ^front[] } # ---------- the server ---------- @back[][message] ^websocket:accept[] ^while(true){ # wait for a message from the browser, but not longer than a second $message[^websocket:receive(0.05)] ^if($message is hash){ ^if($message.type eq close){ ^break[] } ^answer[$message] } $counter($counter+1) ^send_status[] } @answer[message] ^if($message.type eq binary){ ^send[ $.type[answer] $.text[got $message.data.size bytes] ] }($message.data eq ping){ ^send[ $.type[pong] ] }{ ^send[ $.type[answer] $.text[$message.data?] ] } # what the server tells about itself: the time and resources usage @send_status[] ^send[ $.type[status] $.counter($counter) $.time[^date:sql-string[].^eval($status:rusage.tv_usec/1000)[%03.0f]] $.utime($status:rusage.utime) $.used($status:memory.used) $.allocated($status:memory.ever_allocated_since_compact) ] @send[message] ^websocket:send[^json:string[$message]] # ---------- the page ---------- @front[]
Connection: connecting... (to connect again, reload the page)
Server: nothing yet