Skip to content

Instantly share code, notes, and snippets.

@DanielVartanov
Created May 14, 2016 12:23
Show Gist options
  • Save DanielVartanov/c7dcb3713df6960272887ab54265dfdd to your computer and use it in GitHub Desktop.
Save DanielVartanov/c7dcb3713df6960272887ab54265dfdd to your computer and use it in GitHub Desktop.
defmodule HTTPServer do
def receive_http_request(socket) do
{:ok, data} = :gen_tcp.recv(socket, 0)
case data do
"\r\n" ->
IO.puts("Message received")
_ ->
receive_http_request(socket)
end
end
def send_http_response(client_socket) do
response_text = "hello world"
send_http_line(client_socket, "HTTP/1.1 200 OK")
send_http_line(client_socket, "Server: Dummy Elixir script")
send_http_line(client_socket, "Content-Type: text/plain; charset=us-ascii")
send_http_line(client_socket, "Content-Length: #{String.length(response_text) + 1}")
send_http_line(client_socket, "Connection: close")
send_http_line(client_socket, "\r")
send_http_line(client_socket, response_text)
end
defp send_http_line(client_socket, line) do
:ok = :gen_tcp.send(client_socket, line <> "\n")
end
end
{:ok, server_socket} = :gen_tcp.listen(3128, [:binary, packet: :line, active: false, reuseaddr: true])
{:ok, client_socket} = :gen_tcp.accept(server_socket)
IO.puts("Client connected")
HTTPServer.receive_http_request(client_socket)
HTTPServer.send_http_response(client_socket)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment