gpt4 book ai didi

ios - 使用 CFStreamCreatePairWithSocketToHost 的 TCP 套接字连接不工作

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

我是 swift 编程的新手。我正在尝试从我的 ios 应用程序连接到服务器套接字。我有一个 View Controller ,在一个按钮操作中,我调用了连接到套接字服务器的函数

let socketConn = Connection();
socketConn.connect();

我已经在 Connection 类中将委托(delegate)设置为 self,但是在连接到服务器套接字后我的流函数没有被触发。

class Connection : NSObject, NSStreamDelegate {
let serverAddress: CFString = "192.168.1.104"
let serverPort: UInt32 = 5012

private var inputStream: NSInputStream!
private var outputStream: NSOutputStream!

func connect() {
println("connecting...")

var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?

CFStreamCreatePairWithSocketToHost(nil, self.serverAddress, self.serverPort, &readStream, &writeStream)

self.inputStream = readStream!.takeRetainedValue()
self.outputStream = writeStream!.takeRetainedValue()

self.inputStream.delegate = self
self.outputStream.delegate = self

self.inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
self.outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)

self.inputStream.open()
self.outputStream.open()
}

func stream(stream: NSStream, handleEvent eventCode: NSStreamEvent) {
println("stream event")
}
}

谁能帮我调试为什么在连接时调用流函数?

最佳答案

我正在使用 NSStream 类的 getStreamsToHostWithName 函数。它比 CFStreamCreatePairWithSocketToHost

更简单和更好
 func initNetworkCommunication() {

print("connecting...")

let serverAddress = "gzoa.vps.infomaniak.com"
let serverPort = 1234

NSStream.getStreamsToHostWithName(serverAddress, port: serverPort, inputStream: &inputStream, outputStream: &outputStream)

self.inputStream!.delegate = self
self.outputStream!.delegate = self

self.inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
self.outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)

self.inputStream!.open()
self.outputStream!.open()
}

关于ios - 使用 CFStreamCreatePairWithSocketToHost 的 TCP 套接字连接不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31900245/

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