0

In Client :

I will call send() function to pass int number and string in swift client.

The int number has already transformed to [UInt8] type.

func send(number: [UInt8], string: String) {
     var buf = Array(repeating: UInt8(0), count: 1024)
     let data = string.data(using: .utf8)!
     data.copyBytes(to: &buf, count: data.count)

     outputStream?.write(number, maxLength: number.count) // send int number
     outputStream?.write(buf, maxLength: buf.count) // send JSON string
 }

In Server:

I want to send data to c# server.

dataReceive() function will receive the data sent by client.

private void dataReceive() {
    if(reader != null) { // reader is a BEBinaryReader 

        try {
            int number = reader.ReadInt32();
            Console.WriteLine(number);
                       ...
            String str = reader.ReadString();
            Console.WriteLine(str);
        } catch(Exception e) {
            Console.WriteLine(e.Getype());
        }
    }
}

The server can successfully receive int number. However, it will occur exception when receiving string.

The exception is OutOfMemory exception, but the string data I send is just a simple Json string like {"id": 0, "name": "Andy"}

Hope anyone who understands how to send data between swift and c# can help me. Thanks!

haohao
  • 81
  • 1
  • 8
  • I expect your problem is *Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.* as explained in [ReadString](https://msdn.microsoft.com/en-us/library/system.io.binaryreader.readstring(v=vs.110).aspx) – rene Jan 30 '18 at 08:59
  • This can help: https://stackoverflow.com/questions/19710688/binaryreader-readstring-specifying-length – rene Jan 30 '18 at 09:37
  • Thank you all for the reply. I finally use ReadChar() and read each char in while loop and append to char array then transform the char array to string. – haohao Feb 02 '18 at 08:48

0 Answers0