import Network
@objc protocol TCPConnectionDelegate {
@objc optional func deviceStatusUpdated(isUpdated:Bool)
@objc optional func deviceSwitchToNetwork(deviceId:String)
@objc optional func TcpConnectionState(state:String,ip:String)
}
class TCPConnection:NSObject{
var delegate:TCPConnectionDelegate?
var connection: NWConnection?
final func start(host:NWEndpoint.Host) {
connection = NWConnection(host: host, port: 1234, using: .tcp)
connection!.stateUpdateHandler = self.stateDidChange(to:)
self.setupReceive(on: connection!)
connection!.start(queue: .main)
//self.connection = connection
}
func stateDidChange(to state: NWConnection.State) {
var ipAddressWithPort = connection!.endpoint.debugDescription
let ip = ipAddressWithPort.components(separatedBy: ":")
switch state {
case .setup:
break
case .waiting(let error):
print("Errrooor",error)
self.delegate?.TcpConnectionState!(state: error.localizedDescription, ip: ip[0])
//self.connectionDidFail(error: error)
case .preparing:
break
case .ready:
print("Readddy",connection?.endpoint.debugDescription)
print("IPAADERESS",ip[0])
self.delegate?.TcpConnectionState!(state: "Connected",ip: ip[0])
case .failed(let error):
print("FAiled",error)
self.delegate?.TcpConnectionState!(state: error.localizedDescription, ip: ip[0])
case .cancelled:
break
}
}
func setupReceive(on connection: NWConnection) {
connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { (data, contentContext, isComplete, error) in
if let data = data, !data.isEmpty {
print("Received:", String(data: data, encoding: .utf8) )
let stringData = String(data: data, encoding: .utf8)
let data = stringData!.data(using: .utf8)
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String:Any]
print("REsponseeeeData",json)
}catch{
}
}
if isComplete {
self.connectionDidEnd()
} else if let error = error {
self.connectionDidFail(error: error)
} else {
self.setupReceive(on: connection)
}
}
}
var didStopCallback: ((Error?) -> Void)? = nil
private func connectionDidFail(error: Error) {
print("connection did fail, error: \(error)")
stop(error: error)
}
private func connectionDidEnd() {
print("connection did end")
stop(error: nil)
}
private func stop(error: Error?) {
connection!.stateUpdateHandler = nil
connection!.cancel()
if let didStopCallback = didStopCallback {
self.didStopCallback = nil
didStopCallback(error)
}
}
func sendStreamOriented(connection: NWConnection, data: Data) {
connection.send(content: data, completion: .contentProcessed({ error in
if let error = error {
print("Errrorrrr",error)
// self.connectionDidFail(error: error)
}
}))
}
func sendEndOfStream(connection: NWConnection) {
connection.send(content: nil, contentContext: .defaultStream, isComplete: true, completion: .contentProcessed({ error in
if let error = error {
print("Errrorrrr11111",error)
// self.connectionDidFail(error: error)
}
}))
}
func sendMsg(message: [String:Any]) {
let json = try? JSONSerialization.data(withJSONObject: message, options: .prettyPrinted)
guard let jsnStr = String(data: json!, encoding: .utf8) else { return }
print("ekdhkhfkehflhf",jsnStr)
let msg = jsnStr + "\r\n"
let data: Data? = msg.data(using: .utf8)
connection!.send(content: data, completion: .contentProcessed { (sendError) in
if let sendError = sendError {
print("\(sendError)")
}
})
self.setupReceive(on: connection!)
}
func cancel() {
connection!.cancel()
}
}