How to use socket in swift (connect, send and get message)

I am new fast. I want to make chat for iphone, so I need to use the sokect client. how to do it. give me advice or plz example. 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 changing 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") }) }) } 
+5
source share
2 answers

I am using SwiftSocket https://github.com/swiftsocket/SwiftSocket to connect TCP . It is easy to use. For example, to use it (I add comments to it):

I have my shell for working with this library, and this is the method of sending a request and receiving a 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) } } 
+5
source

NSStream or a third-party API. My favorite CocoaAsyncSocket , I myself am also working on a fast version of Swidis (Beta Yet)

Also, to mention CocoaAsyncSocket, you will need to enable bridge-header.h to use as fast.

0
source

Source: https://habr.com/ru/post/1234865/


All Articles