0
func onSocket(sock: AsyncSocket!, didConnectToHost host: String!, port: UInt16) {
    print("+++++++++++++ onSocket +++++++++++++")

    var data:NSData = NSData() ///Users/gameover/Works/Apple/SocketLab/SocketLab/SocketUtil.swift:33:13: Variable 'data' was never mutated; consider changing to 'let' constant
    let loginIn = UserLoginIn.Builder()
    loginIn.setId(Int32(3))
        .setUsername("nothing")
        .setPassword("123456")

    do {
        let loginInBuild = try loginIn.build()
        print(try loginInBuild.encode())
        let length = loginInBuild.serializedSize()
        let msg:NSMutableData = NSMutableData(length: Int(length + length.computeInt32SizeNoTag()))!

        let stream = CodedOutputStream(data: msg)
        try loginInBuild.writeToCodedOutputStream(stream)

        try stream.writeRawData(data)
        print(NSString(data: data, encoding: NSUTF8StringEncoding))
        print("\(data.length) \(loginInBuild.serializedSize())") // this output: 0 19 why?
    } catch {
        print(error)
    }

    client.writeData(data, withTimeout: 0, tag: 0)
    client.readDataWithTimeout(10, tag: 0)
}

When after this : try stream.writeRawData(data) ; the data.length still 0; How to write it in NSData and add a package length in the package header. I will add

try stream.writeInt32NoTag(loginInBuild.serializedSize())

in front of

try loginInBuild.writeToCodedOutputStream(stream)

I don't know if it correct?
Any helps? Thanks!

Nothing
  • 1
  • 2

1 Answers1

0

you should create your proto and get its size

guard let loginInBuild = try? UserLoginIn.Builder().setId(Int32(3)).setUsername("nothing").setPassword("123456").build() else { return }
let length = loginInBuild.serializedSize()

then create delimiter with proper size

let array = [length]
let delimiter = NSData(bytes: arr, length: arr.count * sizeof(Int32))

next create NSMutableData with delimiter and append your protocol buffer.

let pData = NSMutableData(data: delimiter)
pData.appendData(loginInBuild)

each time put delimiter first then proto. you can now stream the pData

server backend will read the stream and get the delimiter data first. from this the size of incomming protocol buffer will be determined, so it can init the proto object with right size and data. if you keep sending multiple successive protos it will always get delimiter then proto.

ha100
  • 1,563
  • 1
  • 21
  • 28