import socket_c
+# Portal for communication between two machines
class Socket
+ # IPv4 address the socket is connected to
+ # Formatted as xxx.xxx.xxx.xxx
var address: String
+
+ # Hostname of the socket connected to self
+ # In C : The real canonical host name (e.g. example.org)
var host: nullable String
+
+ # Port open for the socket
var port: Int
+
+ # Underlying C socket
private var socket: FFSocket
+
+ # Underlying C socket
private var addrin: FFSocketAddrIn
# Guard for errors
# this flag will be set to false.
var still_alive = true # Note : HUGE SUCCESS
+ # Creates a socket connection to host `thost` on port `port`
init stream_with_host(thost: String, tport: Int)
do
socket = new FFSocket.socket( new FFSocketAddressFamilies.af_inet, new FFSocketTypes.sock_stream, new FFSocketProtocolFamilies.pf_null )
port = addrin.port
end
+ # Creates a server socket on port `tport`
init stream_with_port(tport: Int)
do
socket = new FFSocket.socket( new FFSocketAddressFamilies.af_inet, new FFSocketTypes.sock_stream, new FFSocketProtocolFamilies.pf_null )
host = null
end
- init primitive_init(h: FFSocketAcceptResult)
+ # Creates a client socket, this is meant to be used by accept only
+ private init primitive_init(h: FFSocketAcceptResult)
do
socket = h.socket
addrin = h.addrIn
return poll_in(events, 0).length == 0
end
+ # Establishes a connection to socket addrin
+ #
+ # REQUIRES : self.still_alive
fun connect: Bool do
assert still_alive
return socket.connect(addrin) >= 0
end
+ # Write a message to connected socket
+ #
+ # Returns `true` if the `msg` was sent, `false` otherwise
+ #
+ # If not socket.sill_alive, false will be returned
fun write(msg: String): Bool do
if not still_alive then return false
return socket.write(msg) >= 0
end
+ # Read from connected socket
+ #
+ # If the socket is disconnected, an empty string will be returned
fun read: String do
if not still_alive then return ""
return socket.read
end
+ # Close connection
+ #
+ # Returns : `true` if the close was successful, `false` otherwise
fun close: Bool do
if not still_alive then return true
if socket.close >= 0 then
return false
end
+ # Associates the socket to a local address and port
+ #
+ # Returns : `true` if the socket could be bound, `false` otherwise
fun bind: Bool do
if not still_alive then return false
return socket.bind(addrin) >= 0
end
+ # Sets the socket as ready to accept incoming connections, `size` is the maximum number of queued clients
+ #
+ # Returns : `true` if the socket could be set, `false` otherwise
fun listen(size: Int): Bool do
if not still_alive then return false
return socket.listen(size) >= 0
end
+ # Accepts an incoming connection from a client
+ # This creates a new socket that represents the connection to a client
+ #
+ # Returns : the socket for communication with the client
+ #
+ # REQUIRES : self.still_alive
fun accept: Socket do
assert still_alive
return new Socket.primitive_init(socket.accept)