Last active
October 31, 2021 12:11
-
-
Save ashleyconnor/43e8b0ea0f46c3745f35 to your computer and use it in GitHub Desktop.
Elixir Socket Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule SocketPlayground do | |
def listen(port) do | |
listen(port, &handler/1) | |
end | |
def listen(port, handler) do | |
IO.puts "listen" | |
Socket.TCP.listen!(port, packet: :line) | |
|> accept(handler) | |
end | |
def accept(listening_socket, handler) do | |
IO.puts "accept" | |
socket = Socket.TCP.accept!(listening_socket) | |
spawn(fn -> handle(socket, handler) end) | |
accept(listening_socket, handler) | |
end | |
def handle(socket, handler) do | |
IO.puts "handle" | |
incoming = Socket.Stream.recv!(socket) | |
socket |> Socket.Stream.send!(handler.(incoming)) | |
handle(socket, handler) | |
end | |
def handler(line) do | |
String.upcase(line) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment