I've written a server with Python (Twisted) and now want to connect it with iOS, but having some trouble.

This is how I connect to the server:

CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", 3000, &readStream, &writeStream);
inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];

The problem comes with the RunLoop. Imagine that I wan't to send to the server one message. Then I would do:

NSData *data = [[NSData alloc] initWithData:[message dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];

BUT what if I wan't to send TWO messages, one after the other? Then I could run the code with message1 and message2... but then what the client really sends is a concatenation of message1+message2, not two different messages. I guess this is because I write the messages to the outputStream in the same "loop", so when the stream finally decides to send the data, it sends both... I can't figure out any solution. The same happens if SERVER sends more than one message to CLIENT "very fast". What should I do?

有帮助吗?

解决方案

Define the "protocol" - basically a "grammar" which defines the "language" which will be understood by the participants.

The simplest approach would be to define tokens and separators and a corresponding parser.

For example you might define a message consisting of a single char, and multiple messages will be separated by one or more spaces. Then you can send this over the wire:

A B C D E

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top