import gleam/bytes_builder
import gleam/erlang/process
import gleam/int
import gleam/io
import gleam/iterator
import gleam/option.{None, Some}
import gleam/otp/actor
import gleam/otp/task
import glisten
pub const clrf = <<"\r\n":utf8>>
type MyMessage {
Integer(i: Int)
String(s: String)
}
pub fn main() {
io.println("Logs from your program will appear here!")
let int_subject = process.new_subject()
let string_subject = process.new_subject()
let selector =
process.new_selector()
|> process.selecting(int_subject, Integer)
|> process.selecting(string_subject, String)
let assert Ok(subject) =
glisten.handler(fn(_conn) { #(Nil, Some(selector)) }, fn(msg, state, conn) {
case msg {
glisten.Packet(_) -> io.debug("Received a packet")
glisten.User(Integer(some_int)) ->
io.debug("Received a user message int: " <> int.to_string(some_int))
glisten.User(String(s)) ->
io.debug("Received a user message string: " <> s)
}
let assert Ok(_) =
bytes_builder.new()
|> bytes_builder.append(<<"HTTP/1.1 200 OK":utf8, clrf:bits>>)
|> bytes_builder.append(clrf)
|> glisten.send(conn, _)
actor.continue(state)
})
|> glisten.serve(4221)
task.async(fn() {
process.sleep(1000)
process.send(int_subject, 42)
process.send(string_subject, "Hello, world!")
})
iterator.repeatedly(fn() {
case process.select(selector, 5000) {
Ok(Integer(some_int)) ->
io.debug("Received a user message int: " <> int.to_string(some_int))
Ok(String(s)) -> io.debug("Received a user message string: " <> s)
Error(_) -> io.debug("ERROR")
}
})
|> iterator.run
process.sleep_forever()
}
These messages are (naturally since the subject is created on the initial process) not sent to the handler. How can we achieve this?
These messages are (naturally since the subject is created on the initial process) not sent to the handler. How can we achieve this?