2

我正在尝试将数据发送到 OutputStream 以与另一台设备通信。(为此我使用外部附件框架)但该功能不起作用。我有错误找不到成员“写”。我希望有人可以帮助我找到解决方案。谢谢你。

func _writeData() {

    while (_session.outputStream.hasSpaceAvailable && _write.length > 0) {
    var bytesWritten: Int = _session?.outputStream.write(_write.bytes, _write.length);
        if(bytesWritten == -1){
            println("write error");
            break;
        }
        else if (bytesWritten > 0){
            _write.replaceBytesInRange(NSMakeRange(0, bytesWritten), withBytes: nil, length: 0);
        }
    }
}

//high level write data method
func writeData(data: NSData) {
    if(_write == nil) {
        _write = NSMutableData.alloc();
    }
    _write.appendData(data);
    self._writeData();
}

错误--------> var bytesWritten: Int = _session?.outputStream.write(_write.bytes, _write.length);

有我打开和关闭会话的功能

//打开与附件的会话并在默认运行循环上设置输入和输出流 func openSession(accessory: EAAccessory, withProtocolString protocolString: String) -> ObjCBool​​{

    _session = EASession(accessory: accessory, forProtocol: protocolString);

    if(_session != nil) {

        _session.inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode);
        _session.inputStream.open()

        _session.outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode);
        _session.outputStream.open();

    } else {
        println("Creating session failed");
    }
    return (_session != nil);
}

//close the session with the accessory
func closeSession() {

    _session.inputStream.close();
    _session.inputStream.removeFromRunLoop(NSRunLoop(), forMode: NSDefaultRunLoopMode);

    _session.outputStream.close();
    _session.outputStream.removeFromRunLoop(NSRunLoop(), forMode: NSDefaultRunLoopMode);
}
4

1 回答 1

2

after testing many things, I have been able to write to the socket, here is my code:

    var inputStream: NSInputStream?
    var outputStream: NSOutputStream?

    NSStream.getStreamsToHostWithName("localhost", port: 8443, inputStream: &inputStream, outputStream: &outputStream)
    outputStream?.open()
    inputStream?.open()
    //while(true){
      //get input
    //}
    let data: NSData = "this is a test string".dataUsingEncoding(NSUTF8StringEncoding)!
    outputStream?.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)

you can test it using net cat

nc -l 8443
于 2014-10-19T17:21:54.117 回答