gpt4 book ai didi

ios - Swift 使用 GCDAsyncSocket 创建套接字客户端

转载 作者:行者123 更新时间:2023-11-29 01:25:48 25 4
gpt4 key购买 nike

如何使用 Swift 语言通过 GCDAsyncSocket 创建套接字客户端。我使用以下代码:

class MySocketClient: GCDAsyncSocketDelegate{
let addr = "192.168.131.218"
let port :UInt16 = 8000
var inp :NSInputStream?
var out :NSOutputStream?
var bsocket: GCDAsyncSocket!
var err :NSError?

func initClient(name: String) ->String{
bsocket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
return "init result:"+name
}

func connect(){
if(!bsocket.connectToHost(addr, onPort: port, error: nil)){
println("Error.")
}else{
println("Connecting...")

}
}
}

但是奇怪的是,结果

bsocket.connectToHost(addr, onPort: port, error: nil) always return true.

无论我更改IP地址或端口都无法使用。

为什么?创建套接字客户端并使用它向服务器接收/发送数据的正确方法是什么?

最佳答案

connectToHost 返回 true,因为连接尝试已成功启动。

建立连接后,将调用委托(delegate)方法socket:didConnectToHost:port:

来自 connectToHost 的文档:

This method will return NO if an error is detected, and set the error pointer (if one was given). Possible errors would be a nil host, invalid interface, or socket is already connected.

If no errors are detected, this method will start a background connect operation and immediately return YES. The delegate callbacks are used to notify you when the socket connects, or if the host was unreachable.

关于ios - Swift 使用 GCDAsyncSocket 创建套接字客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34040203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com