Last active
August 29, 2015 14:14
-
-
Save guilleiguaran/67f49b3510113fa2f5bc to your computer and use it in GitHub Desktop.
TCP/IP Time server
This file contains 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
%%%---------------------------------------------------------------------- | |
%%% File : time_server.erl | |
%%% Author : Claes Wikstrom <klacke@erix.ericsson.se> | |
%%% Purpose : | |
%%% Created : 3 Nov 1998 by Claes Wikstrom <klacke@erix.ericsson.se> | |
%%%---------------------------------------------------------------------- | |
-module(time_server). | |
-author('klacke@erix.ericsson.se'). | |
-export([start/0, loop0/1]). | |
-define(PORTNO, 2345). | |
start() -> | |
start(?PORTNO). | |
start(Pno) -> | |
spawn(?MODULE, loop0, [Pno]). | |
loop0(Port) -> | |
case gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}]) of | |
{ok, LSock} -> | |
loop(LSock); | |
_ -> | |
stop | |
end. | |
loop(Listen) -> | |
case gen_tcp:accept(Listen) of | |
{ok, S} -> | |
gen_tcp:send(S, io_lib:format("~p~n", [{date(), time()}])), | |
gen_tcp:close(S), | |
loop(Listen); | |
_ -> | |
loop(Listen) | |
end. |
This file contains 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 TimeServer do | |
@portno 2345 | |
def start do | |
start(@portno) | |
end | |
defp start(pno) do | |
spawn(__MODULE__, :loop0, [pno]) | |
end | |
def loop0(port) do | |
case :gen_tcp.listen(port, [:binary, packet: 0, active: false]) do | |
{:ok, socket} -> loop(socket) | |
_ -> :stop | |
end | |
end | |
def loop(listen_socket) do | |
case :gen_tcp.accept(listen_socket) do | |
{:ok, socket} -> | |
:gen_tcp.send(socket, "#{inspect(:erlang.date())} #{inspect(:erlang.time())}") | |
:gen_tcp.close(socket) | |
loop(listen_socket) | |
_ -> loop(listen_socket) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment