gpt4 book ai didi

为 NSStream 快速创建字节缓冲区持有者

转载 作者:搜寻专家 更新时间:2023-10-30 22:23:35 24 4
gpt4 key购买 nike

Ray Wenderlich tutorial on sockets为了从 Objective-C 中的输入流中读取字节,我们做了

uint8_t buffer[1024];
int len;

while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {

NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

if (nil != output) {
NSLog(@"server said: %@", output);
}

在 Swift 中我尝试了以下但没有成功

        if (stream == inputStream) {
// var buffer = Array<UInt8>(count: 1024, repeatedValue: 0)
var buffer : UnsafeMutablePointer<UInt8>
var len : Bool

while (inputStream?.hasBytesAvailable == true) {
len = inputStream?.getBuffer(buffer, length: sizeofValue(buffer))

if (len) {
var output = String(NSString(bytes: buffer, length: sizeofValue(buffer), encoding: NSASCIIStringEncoding))

}
}
}

最佳答案

您可以使用 Array<UInt8>作为缓冲区并按原样传递 documented in Using Swift with Cocoa and Objective-C :

let bufferSize = 1024
var buffer = Array<UInt8>(count: bufferSize, repeatedValue: 0)

let bytesRead = inputStream.read(&buffer, maxLength: bufferSize)
if bytesRead >= 0 {
var output = NSString(bytes: &buffer, length: bytesRead, encoding: NSUTF8StringEncoding)
} else {
// Handle error
}

-[NSInputStream read:maxLength:]返回一个数字,指示它读取了多少字节(如果它 >= 0)或者是否有错误(如果它是负数)。您应该相应地检查返回值。

关于为 NSStream 快速创建字节缓冲区持有者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25476770/

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