Skip to content

Instantly share code, notes, and snippets.

@yfuruyama
Created July 11, 2015 08:59
Show Gist options
  • Save yfuruyama/97a43dfa3fd7e05d32f7 to your computer and use it in GitHub Desktop.
Save yfuruyama/97a43dfa3fd7e05d32f7 to your computer and use it in GitHub Desktop.
defmodule ChatServer do
def accept(port) do
{:ok, sock} = :gen_tcp.listen(port, [:binary, packet: :line, active: false, reuseaddr: true])
loop_accept(sock, [])
end
defp loop_accept(sock, queue) do
{:ok, client} = :gen_tcp.accept(sock)
queue = queue ++ [client]
case queue do
[first | [second | []]] ->
IO.puts "Found chat user!"
spawn_link(fn -> serve(first, second) end)
spawn_link(fn -> serve(second, first) end)
queue = []
_ ->
IO.puts "waiting another connection..."
end
loop_accept(sock, queue)
end
defp serve(sock, sock2) do
sock
|> read_line()
|> write_line(sock2)
serve(sock, sock2)
end
defp read_line(sock) do
{:ok, line} = :gen_tcp.recv(sock, 0)
line
end
defp write_line(line, sock) do
:gen_tcp.send(sock, line)
end
end
ChatServer.accept(4040)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment