Search code examples
socketsstreamfactor-lang

How do I write to a duplex stream?


Suppose I have a Super Simple Socket Server that accepts connections on a port at localhost:

: server-new ( port -- stream ) f swap <inet4> utf8 <server> accept drop ;

And I can use it like:

IN: scratchpad 1204 server-new 

Which waits for a connection. In a terminal:

$ curl localhost:1204
_ 

Which then waits for the server to reply. server-new leaves a duplex-stream on the stack.

T{ duplex-stream
    { in
        T{ decoder
            { stream
                T{ input-port
                    { handle T{ fd { fd 36 } } }
                    { buffer
                        T{ buffer
                            { size 65536 }
                            { ptr ALIEN: 1a44530 }
                        }
                    }
                }
            }
            { code utf8 }
        }
    }
    { out
        T{ encoder
            { stream
                T{ output-port
                    { handle T{ fd { fd 36 } } }
                    { buffer
                        T{ buffer
                            { size 65536 }
                            { ptr ALIEN: 1d42b30 }
                        }
                    }
                }
            }
            { code utf8 }
        }
    }
}

I want to write a string to the client. How do I do this?

It seems like with-stream or something would be the answer, but that just consumes the stream object and nothing gets written to my curl client.


Solution

  • It's probably missing a flush somewhere:

    [ "hello from Factor" print flush ] with-stream
    

    Also notice that with-stream will close the stream when the quotation finishes. If you want to leave it open, use with-stream* instead.