Created
July 11, 2015 07:45
-
-
Save yfuruyama/3f7daf0b588211d62eb6 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 EchoServer 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) do | |
| {:ok, client} = :gen_tcp.accept(sock) | |
| serve(client) | |
| loop_accept(sock) | |
| end | |
| defp serve(sock) do | |
| sock | |
| |> read_line() | |
| |> write_line_with_hello(sock) | |
| serve(sock) | |
| end | |
| defp read_line(sock) do | |
| {:ok, line} = :gen_tcp.recv(sock, 0) | |
| line | |
| end | |
| defp write_line_with_hello(line, sock) do | |
| write_line("Hai! " <> line, sock) | |
| end | |
| defp write_line(line, sock) do | |
| :gen_tcp.send(sock, line) | |
| end | |
| end | |
| EchoServer.accept(4040) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment