我对套接字编程还很陌生,想从一个简单的TCP-Client Application开始。我用几个测试套接字应用程序对其进行了测试。它始终会连接并成功发送第一条消息,但不会收到任何消息。到目前为止,这是我的代码,希望您可以帮助我解决此问题:
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()
}
}