Created
April 13, 2020 07:15
-
-
Save wizard1066/916329f03efccd34231c8f5865c3e9ca to your computer and use it in GitHub Desktop.
ddwtp12
This file contains hidden or 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
import UIKit | |
import Network | |
class Connect: NSObject { | |
private var talking: NWConnection? | |
private var listening: NWListener? | |
func listenUDP( port: Int) { | |
let port2U = NWEndpoint.Port.init(integerLiteral: NWEndpoint.Port.IntegerLiteralType(port)) | |
do { | |
self.listening = try NWListener(using: .udp, on: port2U) | |
self.listening?.stateUpdateHandler = {(newState) in | |
switch newState { | |
case .ready: | |
print("ready") | |
default: | |
break | |
} | |
} | |
self.listening?.newConnectionHandler = {(newConnection) in | |
newConnection.stateUpdateHandler = {newState in | |
switch newState { | |
case .ready: | |
print("new connection") | |
self.receive(on: newConnection) | |
default: | |
break | |
} | |
} | |
newConnection.start(queue: DispatchQueue(label: "new client")) | |
} | |
} catch { | |
print("unable to create listener") | |
} | |
self.listening?.start(queue: .main) | |
} | |
func receive(on connection: NWConnection) { | |
connection.receiveMessage { (data, context, isComplete, error) in | |
if let error = error { | |
print(error) | |
return | |
} | |
if let data = data, !data.isEmpty { | |
let backToString = String(decoding: data, as: UTF8.self) | |
print("b2S",backToString) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment