Skip to content

Commit

Permalink
Merge pull request #14 from noppoMan/socket_management
Browse files Browse the repository at this point in the history
add socketsConnected and closeClientsConnected() to manage sockets
  • Loading branch information
noppoMan committed Jun 25, 2016
2 parents 5064765 + b1464eb commit 089e8b9
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
7 changes: 7 additions & 0 deletions Sources/HTTPStream.swift
Expand Up @@ -25,3 +25,10 @@ extension HTTPStream {
self.send(chunk, timingOut: deadline, completion: completion)
}
}

extension HTTPStream: Equatable {}

public func ==(lhs: HTTPStream, rhs: HTTPStream) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}

36 changes: 24 additions & 12 deletions Sources/Skelton.swift
Expand Up @@ -64,7 +64,11 @@ public final class Skelton {
private let server: TCPServer

// Current connected clients count.
public var clientsConnected: Int = 0
public var clientsConnected: Int {
return socketsConnected.count
}

private var socketsConnected = [HTTPStream]()

/**
- parameter loop: Event loop
Expand Down Expand Up @@ -111,16 +115,31 @@ public final class Skelton {
Loop.defaultLoop.run()
}

public func closeClientsConnected() throws {
for client in socketsConnected {
try client.close()
}
}

/**
Close server handle
*/
public func close() throws {
try server.close()
}

private func onConnection(_ queue: PipeSocket?) {
// TODO need to fix more ARC friendly
let client = HTTPStream()
self.clientsConnected += 1
socketsConnected.append(client)

let unmanaged = Unmanaged.passRetained(client)

client.onClose { [unowned self] in
self.clientsConnected -= 1
client.onClose { [unowned self, unowned client] in
unmanaged.release()
if let index = self.socketsConnected.index(of: client) {
self.socketsConnected.remove(at: index)
}
}

do {
Expand All @@ -146,7 +165,7 @@ public final class Skelton {

let parser = RequestParser()

client.receive { [unowned self] getData in
client.receive { [unowned self, unowned client] getData in
do {
let data = try getData()
if let request = try parser.parse(data) {
Expand Down Expand Up @@ -196,12 +215,5 @@ public final class Skelton {

roundRobinCounter = (roundRobinCounter + 1) % Cluster.workers.count
}

/**
Close server handle
*/
public func close() throws {
try server.close()
}
}

0 comments on commit 089e8b9

Please sign in to comment.