Created
July 11, 2015 08:59
-
-
Save yfuruyama/97a43dfa3fd7e05d32f7 to your computer and use it in GitHub Desktop.
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 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