I am new swift. I want to make chat for iphone so i need to use client sokect. how to make this. give me advise or example plz. I tried this https://github.com/socketio/socket.io-client-swift but not connected and tried this code
let client:TCPClient = TCPClient(addr: "89.236.254.27", port: 9000)
let (success,errmsg) = client.connect(timeout: 1)
if success {
let (success,errmsg) = client.send(str:"Hello World!")
if success {
let data = client.read(1024 * 10)
if let d = data {
if let str = NSString(bytes: d, length: d.count, encoding: NSUTF8StringEncoding) {
print(str)
}
}
} else {
print(errmsg)
}
} else {
print(errmsg)
}
after change this code:
override func viewDidLoad() {
super.viewDidLoad()
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
let client:TCPClient = TCPClient(addr: "89.236.254.27", port: 9000)
var (success, errmsg)=client.connect(timeout: 1)
if success {
var (isSuccess, errorMessage) = client.send(str: "Hello!")
if success {
let data = client.read(1024 * 4)
if let d = data {
if let str = NSString(bytes: d, length: d.count, encoding: NSUTF8StringEncoding) as? String {
print(str)
}
}
} else {
print(errmsg)
}
} else {
print(errmsg)
}
dispatch_async(dispatch_get_main_queue(), {
() -> Void in
print("This is run on the main queue, after the previous code in outer block")
})
})
}
I use the SwiftSocket
https://github.com/swiftsocket/SwiftSocket for TCP
connection. It is easy to use. For example for using it (i add comments to it):
I have my wrapper for work with this lib and this is the method how to send request and get response:
private func blockingRequest(data: String, client: TCPClient?) -> (data: String?, error: ConnectionError?) {
// It use ufter connection
if client != nil {
// Send data
var (isSuccess, errorMessage) = client!.send(str: data)
if isSuccess {
// Read response data
var data = client!.read(1024*10)
if let d = data {
// Create String from response data
if let str = NSString(bytes: d, length: d.count, encoding: NSUTF8StringEncoding) as? String {
return (data: str, error: nil)
} else {
return (data: nil, error: ConnectionError.BadResponseData)
}
} else {
return (data: nil, error: ConnectionError.BadResponseData)
}
} else {
println(errorMessage)
return (data: nil, error: ConnectionError.RequestError)
}
} else {
return (data: nil, error: ConnectionError.RequestError)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With