1

I'm pretty new to socket programming and wanted to start with a simple TCP-Client Application. I tested it with several Test-Socket Apps. It always connects and sends the first message successfully, but it doesn't receive any messages. This is my code so far, I hope you can help me with that:

import Foundation
import UIKit
import CocoaAsyncSocket

class setupViewController: UIViewController, GCDAsyncSocketDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
}

let addr = "192.168.178.43"
let port:UInt16 = 8000
var socket:GCDAsyncSocket!

@IBAction func connectTapped(_ sender: UIButton) {
    print("connecting...")

    socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
    do {
        try socket.connect(toHost: addr, onPort: port)

    } catch let e {
        print(e)
    }

}

func socket(_ socket : GCDAsyncSocket, didConnectToHost host:String, port p:UInt16)
{

    self.socket.readData(toLength: 1024, withTimeout: -1, tag: 0)

    print("Connected to \(addr) on port \(port).")

    let data: Data? = "hey its me".data(using: .utf8)
    self.socket.write(data!, withTimeout: 2, tag: 0)

}

func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {

    print(data)

    self.socket.readData(toLength: 1024, withTimeout: -1, tag: 0)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

0 Answers0