haskell - Communicate with socket from other module -
i'd run websocket server , send messages module it.
so far have managed pass channel module starts server. i'd have globally writefile
can called module @ time.
also i'd have multiple clients sendmessage
. once connection closes assume thread still stays in forever
loop.
server.hs
import network.websockets import control.concurrent import control.monad import data.bytestring createserver :: io (chan bytestring) createserver = chan <- newchan forkio $ runserver "127.0.0.1" 8080 (serverapp chan) ready <- readchan chan -- wait client return chan serverapp :: chan bytestring -> pendingconnection -> io () serverapp chan pending = print "client connected" connection <- acceptrequest pending writechan chan "ready" forever $ msg <- readchan chan sendtextdata connection msg sendmessage :: chan bytestring -> bytestring -> io () sendmessage = writechan
main.hs
main :: io () main = client <- createserver sendmessage client ("hello" :: bytestring)
i ended using mvar
unsafeperformio
. while not recommended the code neat , simple.
createserver :: io () createserver = _ <- forkio $ runserver "127.0.0.1" 8080 serverapp return () serverapp :: pendingconnection -> io () serverapp pending = connection <- acceptrequest pending forever $ msg <- takemvar channel sendtextdata connection msg channel :: mvar bytestring {-# noinline channel #-} channel = unsafeperformio newemptymvar sendmessage :: bytestring -> io () sendmessage = putmvar channel
the code still missing exception handling , works 1 connected client.
Comments
Post a Comment