SwiftSocket icon indicating copy to clipboard operation
SwiftSocket copied to clipboard

About read data.

Open 460122775 opened this issue 10 years ago • 5 comments

//Read data. var data=socket.read(1024*10)

Here, I don`t know the length of data, how can I write the parameter instead of '1024*10' ?

Thanks very much !

460122775 avatar Oct 14 '15 02:10 460122775

Repeat the read until you get fewer bytes than the size of the buffer you gave and collect the result by appending to an array.

segabor avatar May 04 '16 07:05 segabor

@segabor how can we check the buffer size? can u give a sample code?

vineethvijayan avatar Jul 28 '16 13:07 vineethvijayan

@vineethvijayan you just give size supposed to be enough large and the server will keep collecting data received over UDP until the end of stream or when it reaches the limit.

In my case 1024 bytes limit covered all my needs. Here's the snippet from my code I used to receive OSC packets.

    let server = UDPServer(addr: "127.0.0.1", port: 8000)

    while true {
        let (data,remoteip,_)=server.recv(1024)
        print("... receiving data from \(remoteip)")
        if let d=data {
            print("Packet received \(d)")
        }
        server.close()
        break
    }

segabor avatar Jul 28 '16 14:07 segabor

@segabor

let client:TCPClient = TCPClient(addr: "myip", port: 8888)
        let (success, errmsg) = client.connect(timeout: 10)

        if success {
            var data = [UInt8]()
            while true {
                let data1 = client.read(1024*10)
                data = data + data1!
                if data1?.count < 1024*10 {
                    print(data1)

                    var endMarker = NSData(bytes: data as [UInt8], length: data.count)

                    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
                    let documentsDirectory = paths[0] as! String
                    let fileName = "\(documentsDirectory)/1.mp4"

                    endMarker.writeToFile(fileName, atomically: false)

                    client.close()
                    break
                }
            }
        } else {
            print(errmsg)
        }

I am trying to send a file "1.mp4" from a socket server(mac) and it only receives (in phone) a portion of it (just a 2 kb file) and stops and I doing it wrong?

Tried the same with a small file txt files and it saves perfectly

Sorry for the delayed response

vineethvijayan avatar Aug 18 '16 12:08 vineethvijayan

hello. client.read(1024*10) return nil? How can i solve that?

fukemy avatar Sep 21 '18 03:09 fukemy