Skip to content

Instantly share code, notes, and snippets.

@Andrew-Lees11
Created June 29, 2018 09:45
Show Gist options
  • Save Andrew-Lees11/9557b4ff21897b496020509c185e584b to your computer and use it in GitHub Desktop.
Save Andrew-Lees11/9557b4ff21897b496020509c185e584b to your computer and use it in GitHub Desktop.
// ChatServer is a very simple chat server
import Foundation
import KituraWebSocket
import Foundation
class ChatService: WebSocketService {
var gameTimer: Timer!
private var connections = [String: connectionWrapper]()
public func connected(connection: WebSocketConnection) {
connections[connection.id] = connectionWrapper(connection: connection)
}
public func disconnected(connection: WebSocketConnection, reason: WebSocketCloseReasonCode) {
connections.removeValue(forKey: connection.id)
}
public func received(message: Data, from: WebSocketConnection) {
from.close(reason: .invalidDataType, description: "Chat-Server only accepts text messages")
connections.removeValue(forKey: from.id)
}
public func received(message: String, from: WebSocketConnection) {
connections[from.id]?.refreshHeartbeat()
for (connectionId, connectionWrapper) in connections {
if connectionId != from.id {
connectionWrapper.connection.send(message: message)
}
}
}
}
class connectionWrapper {
let connection: WebSocketConnection
var heartbeat: Date
var gameTimer: Timer?
let timeInterval: TimeInterval = 60
init(connection: WebSocketConnection) {
self.connection = connection
self.heartbeat = Date()
self.gameTimer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(checkAlive), userInfo: nil, repeats: true)
}
@objc func checkAlive() {
if heartbeat.timeIntervalSinceNow > timeInterval {
connection.ping()
if heartbeat.timeIntervalSinceNow > timeInterval * 2 {
connection.close()
}
}
}
func refreshHeartbeat() {
heartbeat = Date()
}
deinit {
gameTimer?.invalidate()
}
}
class PingWrapper {
let connection: WebSocketConnection
var heartbeat: Date
var gameTimer: Timer?
let timeInterval: TimeInterval = 60
init(connection: WebSocketConnection) {
self.connection = connection
self.heartbeat = Date()
self.gameTimer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(checkAlive), userInfo: nil, repeats: true)
}
@objc func checkAlive() {
connection.ping()
if heartbeat.timeIntervalSinceNow > timeInterval * 2 {
connection.close()
}
}
func refreshHeartbeat() {
heartbeat = Date()
}
deinit {
gameTimer?.invalidate()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment