Socket
is a simple wrapper around C sockets for Carp.
Installation
(load "https://github.com/carpentry-org/sockets@0.0.1")
Usage
Setting up a socket can be done through setup-server
and
setup-client
or through the macros with-server
and
with-client
.
(let [sock (Socket.setup-server "127.0.0.1" 80)]
; ... work with sock
)
(let [sock (Socket.setup-client "127.0.0.1" 80)]
; ...
)
(Socket.with-server sock "127.0.0.1" 80
; use sock as above
)
(Socket.with-client sock "127.0.0.1" 80
; use sock as above
)
After checking that they are valid using Socket.valid?
, client sockets can
send
and read
right away, whereas server sockets have to listen
and
accept
first. Just like in C!
Alternatively, you can also use the macro with-connection
in the server, like
so:
(Socket.with-server server "127.0.0.1" 80
(Socket.with-connection &server client
(send &client "nice to meet you!")
)
)
If you want a server that accepts connections forever, use while-connection
:
(Socket.with-server server "127.0.0.1" 80
(Socket.while-connection &server client
(send &client "nice to meet you!")
)
)
This will never terminate, unless interrupted by the user or failure.
setup-client
(Fn [(Ref String a), Int] Socket)
setup a client socket to a host using a protocol.
Example:
(Socket.setup-client-for "httpbin.org" "http" 80)
while-connection
Macro
(while-connection from to :rest forms)
create a connection socket from the server from
to
a socket named to
, and then execute forms
forever.
This functions closes the socket automatically at the end.
with-client
Macro
(with-client name host port :rest forms)
create a client socket named name
, connecting to host
and port
, and then execute forms
.
This functions closes the socket automatically at the end.
with-client-for
Macro
(with-client-for name host proto port :rest forms)
create a client socket named name
, connecting to
host
and port
using protocol proto
, and then execute forms
.
This functions closes the socket automatically at the end.
with-connection
Macro
(with-connection from to :rest forms)
create a connection socket from the server from
to
a socket named to
, and then execute forms
.
This functions closes the socket automatically at the end.
with-server
Macro
(with-server name host port :rest forms)
create a server socket named name
, connecting to host
and port
, and then execute forms
.
This functions closes the socket automatically at the end.