2015-10-30 7 views
5

I am new swift. Voglio fare chat per iphone quindi ho bisogno di usare client sokect. come farlo dammi consigli o esempio plz. Ho provato questo https://github.com/socketio/socket.io-client-swift ma non in contatto e provato questo codicecome usare il socket in swift (connettere, inviare e ricevere messaggi)

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

dopo il cambiamento di questo codice:

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

NSStream o di terze parti API. Il mio preferito è [CocoaAsyncSocket] (https://github.com/robbiehanson/CocoaAsyncSocket), anche io sto lavorando su una versione veloce, check it out [Swidis] (https://github.com/FarhadNezhad/Swidis) (Still Beta) – Xrait

+0

Prova questo https://github.com/swiftsocket/SwiftSocket È facile da usare. Se lo proverai e non capirai alcune cose, scrivi qui i commenti –

+0

alex_p grazie per la risposta, SwiftSocket è connesso ma non può ricevere i dati. plz dammi l'esempio –

risposta

5

Uso la SwiftSockethttps://github.com/swiftsocket/SwiftSocket per la connessione TCP. È facile da usare Per esempio per il suo utilizzo (i aggiungere commenti ad esso):

ho il mio wrapper per lavoro con questo lib e questo è il metodo di come inviare richiesta e ottenere risposta:

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

mi sono collegato ma quando invio dati, il server ha ricevuto un messaggio dopo l'arresto del simulatore. perché è? –

+0

@AvazxonUbaydullayev Puoi condividere il link al tuo progetto per vedere qual è il problema, perché è molto difficile dire qualcosa senza codice –

+0

alex_p, ottenere il mio progetto questo link: https://drive.google.com/open?id= 0B3ShmF_Xwo0_eTNhYV83Y3dhOWs. questo progetto condiviso tutti –

0

NSStream o di terze parti API. Il mio preferito è CocoaAsyncSocket, Im lavorando anche su una versione veloce di me, check it out Swidis (ancora in beta)

anche ricordare con CocoaAsyncSocket è necessario includere una bridge-header.h da usare quanto più rapido.

+0

Il benvenuto, spero di alzarmi per votare o controllare :) – Xrait