I’m currently working on a sever-side project that communicates with a server using TCP Sockets.
After a quick search on pursuit, I landed on using purescript-node-net package. I looked at the /tests/ directory to look for examples no how to use sockets in Purescript
and found that node sockets relies on callbacks, such as onError, onData and onClose.
I’m having trouble understanding how to consume callbacks and extract data from them to parent callers.
Consider this example:
import Prelude
import Data.Either (Either(..))
import Data.Maybe (Maybe(..))
import Effect (Effect)
import Effect.Console (errorShow, infoShow, logShow)
import Node.Buffer (toString)
import Node.Encoding (Encoding(..))
import Node.Net.Server as Node.Net.Server
import Node.Net.Socket as Node.Net.Socket
main = do
log "Program started"
socket <- Node.Net.Socket.createConnectionTCP 8080 "localhost" do
infoShow { _message: "Connected to server" }
Node.Net.Socket.onReady socket do
infoShow { _message: "Socket is ready" }
void $ Node.Net.Socket.writeString socket "some JSON data goes here" UTF8 mempty
Node.Net.Socket.onClose socket case _ of
false -> infoShow { _message: "Socket closed without an error" }
true -> errorShow { _message: "Socket closed with an error" }
Node.Net.Socket.onData socket case _ of
Left buffer -> do
bufferString <- toString UTF8 buffer
logShow { _message: "Received some data", bufferString }
Right string -> logShow { _message: "Received some data", string }
Node.Net.Socket.onError socket \err ->
errorShow { _message: "Socket had an error", err }
-- how to access bufferString and err in this scope level???
log "Program finished"
When I run this program, I see “Program started” and immediately “Program finished” and then I see other callbacks execute.
I understand this is how they’re supposed to be. But is there a way to convert these callback to run under Aff so that bufferString and err are exposed?
Something like this in psuedo code:
main = do
log "Program started"
socket <- Node.Net.Socket.createConnectionTCP 8080 "localhost"
resultOrError <- Node.Net.Socket.writeString socket "some JSON data goes here" UTF8 mempty
log "Program finished"
My main goal is to get the values AND guarantee that all callbacks run between “Program started” and “Program finished”.
I hope make explanation makes sense.