Iphone listen a tcp port
ios, port, tcp
Solution
Listening to some TCP port does require some things to set up.
A good choice would be to use Robbie Hanson's CocoaAsyncSocket.
There you'll find an example for Echo Server (in RunLoop/XCode/EchoServer.
True, this XCode project was generated for OSX but you can simply create an empty iOS project and copy-paste most of the code.
There is no 'read until break' functionality though - but it is simple enough to implement while copying data to receive buffer.
EDIT:
You'd typically want to modify `onSocket: didReadData: withTag:`
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length])];
NSString *str = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
if(str)
{
myLabel.text = str;
}
}
Now, this code does not detect `\n` in incoming data. You could for example define an ivar or property `rx_buffer`
NSMutableString *rx_buffer;
which would be built with
rx_buffer = [rx_buffer stringByAppendingString: str];
until you detect `\n` in `str`.
Problem
I read some suggested links from the other answers to similar questions. Article1, Library1, Another SO Question. However, I couldn't figure out how to do the following application. Basically, I send to Iphone's IP and a chosen port (let's say port: 2020) a string. And I want to show this string on the Iphone's UI. So, let's check the following example code: ``` - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString* str; while(true) { str = ReadLineFromPort(2020); myLabel.text = str; } } ``` I expect the `ReadLineFromPort()` method to have the following duty: Read until you see a line break (i.e., '\n') and when you see the line break return the string. (Similar to the C# StreamReader.Readline method.) Any help will be greatly appreciated. Since I'm not a pro IOS developer I need a basic one though.