Skip to content

Instantly share code, notes, and snippets.

@paulofaria
Created April 2, 2016 15:54
Show Gist options
  • Save paulofaria/e1ca03484049bad1849c07a7c889429d to your computer and use it in GitHub Desktop.
Save paulofaria/e1ca03484049bad1849c07a7c889429d to your computer and use it in GitHub Desktop.
do {
let ip = try IP(localAddress: "127.0.0.1", port: 8080)
let serverSocket = try TCPServerSocket(ip: ip)
serverSocket.accept { getClientStream in
do {
let clientStream = try getClientStream()
clientStream.receive(length: Int.max) { getData in
do {
let data = try getData()
print("server received: \(data)")
clientStream.send(data: data) { success in
do {
try success()
} catch {
print("server send error: \(error)")
}
}
} catch {
print("server receive error: \(error)")
}
}
} catch {
print("server accept error: \(error)")
}
}
let clientSocket = try TCPClientSocket(ip: ip)
clientSocket.connect { getClientStream in
do {
let clientStream = try getClientStream()
clientStream.send(data: "hello") { success in
do {
try success()
} catch {
print("client send error: \(error)")
}
}
clientStream.send(data: "world") { success in
do {
try success()
} catch {
print("client send error: \(error)")
}
}
clientStream.receive(length: Int.max) { getData in
do {
let data = try getData()
print("client received: \(data)")
} catch {
print("client receive error: \(error)")
}
}
} catch {
print("client connect error: \(error)")
}
}
main()
} catch {
print(error)
}
// vs
do {
let ip = try IP(localAddress: "127.0.0.1", port: 8080)
co {
do {
let serverSocket = try TCPServerSocket(ip: ip)
let clientStream = try serverSocket.accept()
let data = clientStream.receive(length: Int.max)
print("server received: \(data)")
clientStream.send(data: data)
catch {
print(error)
}
}
let clientSocket = try TCPClientSocket(ip: ip)
let clientStream = try clientSocket.connect()
try clientStream.send(data: "hello")
try clientStream.send(data: "world")
print("client received: \(data)")
} catch {
print(error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment