ios - 从 Swift IOS 套接字获取 InputStream 中的文件

标签 ios swift file sockets inputstream

我想快速从套接字中获取输入流中的文件

从套接字中获取字符串的例子有很多,但没有找到任何获取套接字文件的方法

// To connect to the server
func connect(host: String, port: Int) {

    SwifterHandler.sharedInstance.FilePathSave = SwifterHandler.sharedInstance.rootDoc()

    self.host = host
    self.port = port


    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: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
        self.outputStream!.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)


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

}


// This is a call back func that takes care of I/O from/to the server.
// Read about this func. There are many event codes to handle.
// I just wanted to make it simple.
func stream(aStream: Stream, handleEvent eventCode: Stream.Event) {
    print("Event : \(eventCode)")
    if aStream != inputStream {
        return
    }

    if eventCode == .hasBytesAvailable {
        self.ReadFile()
    }
}

private func ReadFile()
{
    var buffer = [UInt8](repeating: 0, count: 1024)
    if let fh = FileHandle(forWritingAtPath: "\(SwifterHandler.sharedInstance.FilePathSave)/test.png") {
        fh.seekToEndOfFile()
    while (self.inputStream!.hasBytesAvailable){

        let bytesRead: Int = inputStream!.read(&buffer, maxLength: buffer.count)

        if bytesRead >= 0 {



             fh.write(Data(bytes: buffer))

        }
    }



        fh.closeFile()
    }
    SwifterHandler.sharedInstance.SharedFile(path: SwifterHandler.sharedInstance.FilePathSave)
    self.dataReadCallback!("Success Download")
    InstallApp().InstallApplication()
    self.dataReadCallback!("Application Installed")

}

服务器发送文件时不运行ReadFile()

最佳答案

class ViewController: UIViewController,StreamDelegate
{
    var inputstream: InputStream?
    var outputstream: OutputStream?
    var host: String?
    var port: Int?

    override func viewDidLoad()
    {
        super.viewDidLoad()

        let _ = initNetworkCommunication()      
        let word = "Hello are you there->"

        let buf = [UInt8](word.utf8)
        print("This is buf = \(buf))")


        outputstream?.write(buf, maxLength: buf.count)
    }

    func initNetworkCommunication()
    {
        host = "127.0.0.1"      //this is IP number passing as string
        port = 34               //this is port number


        Stream.getStreamsToHost(withName: host!, port: port!,inputStream: &inputstream, outputStream: &outputstream)

        //here we are going to calling a delegate function
        inputstream?.delegate = self as? StreamDelegate
        outputstream?.delegate = self as? StreamDelegate


        inputstream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
        outputstream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)

        inputstream?.open()
        print("Here the input stream will open")

        outputstream?.open()
        print("connected")
    }

    func stream(_ aStream: Stream, handle eventCode: Stream.Event)
    {
        print("we are in delegate method")

        print("EventCode = \(eventCode)")
        switch (eventCode)
        {
        case Stream.Event.openCompleted:
            if(aStream == outputstream)
            {
                print("output:OutPutStream opened")
            }
            print("Input = openCompleted")
            break

        case Stream.Event.errorOccurred:
            if(aStream === outputstream)
            {
                print("output:Error Occurred\n")

            }
            print("Input : Error Occurred\n")
            break

        case Stream.Event.endEncountered:
            if(aStream === outputstream)
            {
                print("output:endEncountered\n")
            }
            print("Input = endEncountered\n")
            break

        case Stream.Event.hasSpaceAvailable:
            if(aStream === outputstream)
            {
                print("output:hasSpaceAvailable\n")
            }

            print("Input = hasSpaceAvailable\n")
            break

        case Stream.Event.hasBytesAvailable:
            if(aStream === outputstream)
            {
                print("output:hasBytesAvailable\n")
            }
            if aStream === inputstream
            {
                print("Input:hasBytesAvailable\n")

                var buffer = [UInt8](repeating: 0, count: 4096)

                //print("input buffer = \(buffer)")
                // sleep(40)

                while (self.inputstream!.hasBytesAvailable)
                {
                    let len = inputstream!.read(&buffer, maxLength: buffer.count)

                    // If read bytes are less than 0 -> error
                    if len < 0
                    {
                        let error = self.inputstream!.streamError
                        print("Input stream has less than 0 bytes\(error!)")
                        //closeNetworkCommunication()
                    }
                    // If read bytes equal 0 -> close connection
                    else if len == 0
                    {
                        print("Input stream has 0 bytes")
                        // closeNetworkCommunication()
                    }


                    if(len > 0)
                        //here it will check it out for the data sending from the server if it is greater than 0 means if there is a data means it will write
                    {
                        let messageFromServer = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)

                        if messageFromServer == nil
                        {
                            print("Network hasbeen closed")
                            // v1.closeNetworkCommunication()
                        }
                        else
                        {
                            print("MessageFromServer = \(String(describing: messageFromServer))")
                        }
                    }
                }
            }

            break

        default:
            print("default block")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

关于ios - 从 Swift IOS 套接字获取 InputStream 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41239081/

相关文章:

ios - 在 UITextView 内占据左角的 UIImageView

swift - 如何使用 swift 在 UIImage 上画线?

windows - 如何检查 Windows .bat 脚本中 32 位 Program Files 文件夹的位置

Java 文件上下文不为 null 会抛出 NullPointerException

xml - iOS 修改本地XML文件

ios - iphone nsoperation 应用程序卡住

ios - 复用 collectionView

iphone - 如何在 Objective-C 中获取当前周数?

swift - 在 Swift 中从单个 tableview 创建两个 segue

swift - 二元运算符 == 不能应用于 swift 中的两个 Int32 操作数