简体   繁体   中英

NSStream seems to some how truncate data

I am pulling my hair out over this. I am sending a few pieces of data to the server, so i put it in the buffer, and then send the buffer. Everything seems fine, but on the server, the string is being cut off, at different points, so for example I get "1234567890123\\0\\0\\0..." instead of "12345678901234567890123456789012".

All the ints work fine, and are transferred fine. Anyone have a clue why the whole message would not come across. The server is reading the whole message off the stream, no bytes remain unread, client sends 68, server gets 68 bytes. Could it be the encoding?

Here is the iPhone code:

int command = 0;
int msgLen =0;
int bytesSent;

(void)memcpy(_data, &command, sizeof(int)); msgLen++; 
(void)memcpy(_data+2, &playerID, sizeof(int)); msgLen++;

NSString *response  = [NSString stringWithString:@"12345678901234567890123456789012"];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSUnicodeStringEncoding]];
(void)memcpy(_data+3, [data bytes], [data length]);
msgLen += [data length];

(void)memcpy(_data+1, &msgLen, sizeof(int)); msgLen++;

bytesSent = [outputStream write:(const uint8_t *)_data maxLength:msgLen];

NSLog(@"sent %d of %d",bytesSent, msgLen);

Here is the C# code

    private void JoinServer(TcpClient client, byte[] buffer)
    {
        int offset = 0;
        int playerid = BitConverter.ToInt32(buffer, offset);
        offset += 4;
        var playerkey = Encoding.Unicode.GetString(buffer, offset, buffer.Length-4);
        System.Diagnostics.Debug.WriteLine(playerkey, "JoinPlayerReceived");

        try
        {

            GetSubscriberByClient(client).PlayerId = playerid;
            SendJoinServerStatus(playerid, playerid);
        }
        catch (Exception)
        {
            SendJoinServerStatus(playerid, 0);
        }

    }

The solution was in the encoding.

After I fixed the encoding, and everything works fine, all strings show up as they were sent from the server, works perfectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM