gpt4 book ai didi

sockets - 如何快速连接到套接字以读取数据并写入数据

转载 作者:搜寻专家 更新时间:2023-10-31 08:34:12 28 4
gpt4 key购买 nike

如何在 swift 中创建一个可以监听和写入的套接字? GCDAsyncSocket 是正确的方法还是其他方法?我使用 CFStreamCreatePairWithSocketToHost 连接到套接字但无法从中读取数据。

最佳答案

对于那些对 Swift 3 实现感兴趣的人。它被大量引用自 raywenderlich's example进行了一些修改。

func connect() {
Stream.getStreamsToHost(withName: self.address!, port: self.port!, inputStream: &self.inputStream, outputStream: &self.outputStream);

guard let _ = inputStream, let _ = outputStream else {
// your own execption or otherwise
return;
}

self.inputStream?.delegate = self;
self.outputStream?.delegate = self;

self.inputStream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode);
self.outputStream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode);

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

func disconnect() {
if let stream = self.inputStream {
stream.close();
stream.remove(from: RunLoop.current, forMode: RunLoopMode.commonModes);
}
if let stream = self.outputStream {
stream.close();
stream.remove(from: RunLoop.current, forMode: RunLoopMode.commonModes);
}
self.inputStream = nil;
self.outputStream = nil;
}

func write(data:Data) {
let _ = data.withUnsafeBytes { (unsafePointer:UnsafePointer<UInt8>) in
let bytesWritten = self.outputStream?.write(unsafePointer, maxLength: data.count);
};
}

func readAvailableBytes(stream: InputStream) {
var buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: maxReadLength);
while stream.hasBytesAvailable {
let numberOfBytesRead = stream.read(buffer, maxLength: maxReadLength)
if numberOfBytesRead < 0 {
if let _ = stream.streamError {
break
}
}
//Construct the Message object
if(numberOfBytesRead > 0){
let output = String(cString:buffer)
NSLog("server said: %@", output)
} else {
NSLog("empty string from stream")
}

}
buffer.deallocate(capacity: maxReadLength);
}

并确保在您的处理类中实现StreamDelegate 和委托(delegate)方法:

func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
NSLog("Receieve stream event: %d", eventCode.rawValue);
switch (eventCode){
case Stream.Event.errorOccurred:
NSLog("ErrorOccurred")
break;
case Stream.Event.endEncountered:
NSLog("EndEncountered")
break;
case Stream.Event.hasBytesAvailable:
NSLog("HasBytesAvaible");
break;
case Stream.Event.openCompleted:
NSLog("OpenCompleted");
break;
case Stream.Event.hasSpaceAvailable:
NSLog("HasSpaceAvailable");
break;
default:
NSLog("default reached. unknown stream event")
break;
}
}

注意:raywnderlich 的实现有一些变化,特别是在委托(delegate)方法中。

关于sockets - 如何快速连接到套接字以读取数据并写入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28524431/

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