Implement SO_REUSEADDR for asyncnet and asynchttpserver.

This commit is contained in:
Dominik Picheta
2014-11-07 14:48:11 +00:00
parent 96d1543c0d
commit 13e3c0d5bb
3 changed files with 20 additions and 2 deletions

View File

@@ -37,6 +37,7 @@ type
AsyncHttpServer* = ref object
socket: PAsyncSocket
reuseAddr: bool
HttpCode* = enum
Http200 = "200 OK",
@@ -64,9 +65,10 @@ proc `==`*(protocol: tuple[orig: string, major, minor: int],
of HttpVer10: 0
result = protocol.major == major and protocol.minor == minor
proc newAsyncHttpServer*(): PAsyncHttpServer =
proc newAsyncHttpServer*(reuseAddr = true): PAsyncHttpServer =
## Creates a new ``AsyncHttpServer`` instance.
new result
result.reuseAddr = reuseAddr
proc addHeaders(msg: var string, headers: PStringTable) =
for k, v in headers:
@@ -210,6 +212,8 @@ proc serve*(server: PAsyncHttpServer, port: Port,
##
## When a request is made by a client the specified callback will be called.
server.socket = newAsyncSocket()
if server.reuseAddr:
server.socket.setSockOpt(OptReuseAddr, true)
server.socket.bindAddr(port, address)
server.socket.listen()

View File

@@ -60,6 +60,8 @@ import rawsockets
import net
import os
export SOBool
when defined(ssl):
import openssl
@@ -425,6 +427,17 @@ when defined(ssl):
socket.bioOut = bioNew(bio_s_mem())
sslSetBio(socket.sslHandle, socket.bioIn, socket.bioOut)
proc getSockOpt*(socket: AsyncSocket, opt: SOBool, level = SOL_SOCKET): bool {.
tags: [ReadIOEffect].} =
## Retrieves option ``opt`` as a boolean value.
var res = getSockOptInt(socket.fd, cint(level), toCInt(opt))
result = res != 0
proc setSockOpt*(socket: AsyncSocket, opt: SOBool, value: bool,
level = SOL_SOCKET) {.tags: [WriteIOEffect].} =
## Sets option ``opt`` to a boolean value specified by ``value``.
var valuei = cint(if value: 1 else: 0)
setSockOptInt(socket.fd, cint(level), toCInt(opt), valuei)
when isMainModule:
type

View File

@@ -428,7 +428,8 @@ proc close*(socket: Socket) =
elif res != 1:
socketError(socket)
proc toCInt(opt: SOBool): cint =
proc toCInt*(opt: SOBool): cint =
## Converts a ``SOBool`` into its Socket Option cint representation.
case opt
of OptAcceptConn: SO_ACCEPTCONN
of OptBroadcast: SO_BROADCAST