如何在Swift中检测套接字数据包的结尾

时间:2016-07-06 19:45:28

标签: swift sockets

我正在Swift中构建一个HTTP服务器。服务器最终将在Linux上运行,但现在只在Mac OS上编译。

无论如何,我的套接字连接工作正常并且我能够接收数据流,但是我很难找到确定如何检测套接字数据流结束的最佳方法。

我知道有很多方法可以解决这个问题,而且我知道套接字基本上只是吐出纯二进制数据,并且没有"数据包"有一个开始和结束。我的问题是什么是用于检测从请求网页的Web浏览器发送的数据包结束的最佳技术?我知道JSON很容易,但我很好奇客户端何时专门请求网页。

由于

1 个答案:

答案 0 :(得分:0)

InputStream为您做到了这一点,您不必关心它。

尝试使用它:

import Foundation

typealias OnComing = (String) -> (Void)

class SocketClient: NSObject, StreamDelegate {

    var host:String?
    var port:Int?
    var inputStream: InputStream?
    var outputStream: OutputStream?

    var status = false;
    var output = ""
    var bufferSize = 1024;

    var onComing:OnComing!

    func makeCFStreamConnection(host: String, port: Int, onComing:@escaping OnComing) {

        self.host = host
        self.port = port
        self.onComing = onComing

        Stream.getStreamsToHost(withName: host, port: port, inputStream: &self.inputStream, outputStream: &self.outputStream)

        if self.inputStream != nil && self.outputStream != nil {

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

            self.inputStream!.schedule(in: .main, forMode: RunLoopMode.defaultRunLoopMode)
            self.outputStream!.schedule(in: .main, forMode: RunLoopMode.defaultRunLoopMode)

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

        }


    }

    func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
        if aStream === self.inputStream {
            switch eventCode {
            case Stream.Event.errorOccurred:
                break
            case Stream.Event.openCompleted:
                break
            case Stream.Event.hasBytesAvailable:
                break
                read()
            default:
                break
            }
        } else if aStream === self.outputStream {
            switch eventCode {
            case Stream.Event.errorOccurred:
                break
            case Stream.Event.openCompleted:
                break
            case Stream.Event.hasSpaceAvailable:
                break
            default:
                break
            }
        }
    }

    func read() {
        var buffer = [UInt8](repeating: 0, count: bufferSize)
        while (self.inputStream!.hasBytesAvailable) {
            let bytesRead: Int = inputStream!.read(&buffer, maxLength: buffer.count)
            if bytesRead >= 0 {
                output += NSString(bytes: UnsafePointer(buffer), length: bytesRead, encoding: String.Encoding.ascii.rawValue)! as String
            } else {
                print("# Stream read() error")
            }
        }
        self.onComing(output)
    }

    func write(message:String) {
        let encodedDataArray = [UInt8]("\(message)\n".utf8)
        self.outputStream?.write(encodedDataArray, maxLength: encodedDataArray.count)
    }
}

您的问题已通过read()

解决