Last active
December 2, 2017 05:12
-
-
Save markohlebar/72f71b9147e4dad19c23bc7e1d4a9b8b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is our delegate protocol for everything that happens on the server | |
protocol ServerClient: class { | |
func serverDidStart(_ server: Server) | |
func serverDidEnd(_ server: Server) | |
func server(_ server: Server, didReceive packet: Server.Packet) | |
} | |
// This is our server which will handle the socket connection with FreeCrypto socket service | |
class Server { | |
// Our imaginary FreeCrypto service drops data in a dictionary | |
struct Key { | |
static let amount = "amount" | |
} | |
// A packet of data containing amount of crypto | |
struct Packet { | |
var amount: Int | |
} | |
weak var client: ServerClient?; | |
// Connect to FreeCrypto socket service | |
func start() { | |
guard let client = client else { return } | |
client.serverDidStart(self) | |
} | |
// Disconnect from FreeCrypto socket service | |
func end() { | |
guard let client = client else { return } | |
client.serverDidEnd(self) | |
} | |
// Receive data from FreeCrypto socket service | |
func didReceive(data: [String:Int]) { | |
guard let client = client, | |
let amount = data[Server.Key.amount] else { return } | |
let packet = Packet(amount: amount) | |
client.server(self, didReceive: packet) | |
} | |
} | |
// This is our client of the FreeCrypto server, watching as the BTC rolls in. | |
class BitcoinWatcher: ServerClient { | |
func serverDidStart(_ server: Server) { | |
print("BTC here I come 😎") | |
} | |
func serverDidEnd(_ server: Server) { | |
print("Where be my BTC 🤔") | |
} | |
func server(_ server: Server, didReceive packet: Server.Packet) { | |
print("Yay received \(packet.amount) BTC 🔥") | |
} | |
} | |
// Setting up the machinery | |
let server = Server() | |
let bitcoinWatcher = BitcoinWatcher() | |
// We need to set the bitcoin watcher as the client here to receive events | |
server.client = bitcoinWatcher | |
// Simulation of server events... | |
server.start() | |
server.didReceive(data:["amount":10]) | |
server.end() | |
// Prints: | |
// BTC here I come 😎 | |
// Yay received 10 BTC 🔥 | |
// Where be my BTC 🤔 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment