Skip to content

Commit

Permalink
Added GenTCP, with examples
Browse files Browse the repository at this point in the history
  • Loading branch information
Justin Baker authored and josevalim committed Mar 13, 2011
1 parent 6c9d66d commit 1e7a837
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 0 deletions.
5 changes: 5 additions & 0 deletions examples/gen_tcp_client.ex
@@ -0,0 +1,5 @@
Code.require "gen_tcp"
{'ok, tcp} = GenTCP.connect("localhost", 5678, ['binary, {'packet, 0}])
'ok = tcp.send("Some Data")
'ok = tcp.close

24 changes: 24 additions & 0 deletions examples/gen_tcp_server.ex
@@ -0,0 +1,24 @@
Code.require "gen_tcp"

module Server

def do_recv(tcp, sock, bs)
case tcp.recv(sock,0)
match {'ok, b}
do_recv(tcp, sock, [bs, b])
match {'error, 'closed}
{'ok, Erlang.list_to_binary(bs)}
end
end

def start
{'ok, tcp} = GenTCP.listen(5678, ['binary, {'packet, 0}, {'active, false}])

{'ok, sock} = tcp.accept
{'ok, bin} = do_recv(tcp, sock, [])
'ok = tcp.close
IO.puts bin.to_s
end
end

Server.start
72 changes: 72 additions & 0 deletions lib/gen_tcp.ex
@@ -0,0 +1,72 @@
object GenTCP
module Mixin
def listen(port, options)
case Erlang.gen_tcp.listen(port, options)
match { 'ok, sock }
{ 'ok, GenTCP.new(sock) }
match other
other
end
end

def listen(port, options, timeout)
case Erlang.gen_tcp.listen(port, options, timeout)
match { 'ok, sock }
{ 'ok, GenTCP.new(sock) }
match other
other
end
end

def connect(address, port, options)
connect(address, port, options, 0)
end

def connect(address, port, options, timeout)
case Erlang.gen_tcp.connect(address.to_char_list, port, options, timeout)
match { 'ok, sock }
{ 'ok, GenTCP.new(sock) }
match other
other
end
end

end

def constructor(sock)
{'sock: sock}
end
def controlling_process(pid)
Erlang.gen_tcp.controlling_process(@sock, pid)
end
def recv(sock, length)
Erlang.gen_tcp.recv(sock, length)
end
def recv(sock, length, timeout)
Erlang.gen_tcp.recv(sock, length, timeout)
end
def accept
Erlang.gen_tcp.accept(@sock)
end
def accept(timeout)
Erlang.gen_tcp.accept(@sock, timeout)
end
def send(message)
Erlang.gen_tcp.send(@sock, message.to_bin)
end
def close
Erlang.gen_tcp.close(@sock)
end
def shutdown
Erlang.gen_tcp.shutdown(@sock)
end
end
11 changes: 11 additions & 0 deletions test/elixir/gen_tcp_test.ex
@@ -0,0 +1,11 @@
Code.require File.expand_path("../test_helper", __FILE__)
Code.require "gen_tcp"

object GenTcpTest
proto ExUnit::Case

def connect_test
{'error, 'timeout} = GenTCP.connect("google.com", 80, [{'active,false},{'packet,2}])
end

end

0 comments on commit 1e7a837

Please sign in to comment.