如何在swift中使用socket(连接,发送和获取消息)

时间:2015-10-30 12:44:00

标签: swift sockets swift2

我很快乐。我想和iphone聊天,所以我需要使用客户端sokect。怎么做到这一点。给我建议或示例plz。 我试过这个 https://github.com/socketio/socket.io-client-swift 但没有连接 并尝试了这段代码

 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)
     }

更改此代码后:

 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")
         })
     })
 }

2 个答案:

答案 0 :(得分:4)

我使用SwiftSocket https://github.com/swiftsocket/SwiftSocket进行TCP连接。它很容易使用。例如,使用它(我添加注释):

我有使用此lib的包装器,这是如何发送请求和获取响应的方法:

    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)
        }
    }

答案 1 :(得分:0)

NSStream或第三方API。我最喜欢的是CocoaAsyncSocket,我自己也在制作一个快速版本,请查看Swidis(测试版)

另外,对于CocoaAsyncSocket,您需要包含一个bridge-header.h 以用作swift。