socket :: TCPServer :: defaultinit
# A socket listening on a given `port` for incomming connections
#
# Create streams to communicate with clients using `accept`.
class TCPServer
super TCPSocket
private var addrin: NativeSocketAddrIn is noinit
# Create and bind a listening server socket on port `port`
init
do
native = new NativeSocket.socket(new NativeSocketAddressFamilies.af_inet,
new NativeSocketTypes.sock_stream, new NativeSocketProtocolFamilies.pf_unspec)
assert not native.address_is_null
if not native.setsockopt(new NativeSocketOptLevels.socket, new NativeSocketOptNames.reuseaddr, 1) then
closed = true
return
end
addrin = new NativeSocketAddrIn
addrin.family = new NativeSocketAddressFamilies.af_inet
addrin.port = port
addrin.address_any
address = addrin.address.to_s
# Bind it
closed = not bind
end
# Associates the socket to a local address and port
#
# Returns whether the socket has been be bound.
private fun bind: Bool do
return native.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
return native.listen(size) >= 0
end
# Accepts an incoming connection from a client
#
# Create and return a new socket to the client. May return null if not
# `blocking` and there's no waiting clients, or upon an interruption
# (whether `blocking` or not).
#
# Require: not closed
fun accept: nullable TCPStream
do
assert not closed
var native = native.accept
if native == null then return null
return new TCPStream.server_side(native)
end
# Close this socket
fun close
do
# FIXME unify with `SocketStream::close` when we can use qualified names
if closed then return
if native.close >= 0 then
closed = true
end
end
end
lib/socket/socket.nit:219,1--288,3