2022-11-08 10:44:16 +00:00
from socketify import App , AppOptions , OpCode , CompressOptions
2022-11-16 19:28:46 +00:00
2022-11-08 10:44:16 +00:00
def ws_open ( ws ) :
2022-11-16 19:28:46 +00:00
print ( " A WebSocket got connected! " )
# Let this client listen to topic "broadcast"
ws . subscribe ( " broadcast " )
2022-11-08 10:44:16 +00:00
def ws_message ( ws , message , opcode ) :
2022-11-16 19:28:46 +00:00
# Broadcast this message
ws . publish ( " broadcast " , message , opcode )
app = App ( )
app . ws (
" /* " ,
{
" compression " : CompressOptions . SHARED_COMPRESSOR ,
" max_payload_length " : 16 * 1024 * 1024 ,
2023-01-05 12:01:05 +00:00
" idle_timeout " : 60 ,
2022-11-16 19:28:46 +00:00
" open " : ws_open ,
" message " : ws_message ,
# The library guarantees proper unsubscription at close
" close " : lambda ws , code , message : print ( " WebSocket closed " ) ,
2023-01-05 12:01:05 +00:00
" subscription " : lambda ws , topic , subscriptions , subscriptions_before : print ( f ' subscription/unsubscription on topic { topic } { subscriptions } { subscriptions_before } ' ) ,
2022-11-16 19:28:46 +00:00
} ,
)
app . any ( " / " , lambda res , req : res . end ( " Nothing to see here! " ) )
app . listen (
3000 ,
lambda config : print ( " Listening on port http://localhost: %d now \n " % ( config . port ) ) ,
)
app . run ( )