- (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; } }
Reference
Simple iPhone TCP client example not working
http://stackoverflow.com/questions/13834955/simple-iphone-tcp-client-example-not-working
https://github.com/byteclub/SimpleSocketConnection
nc -k -l 45678
iPhone TCP/IP Socket Server/Client Program
http://stackoverflow.com/questions/1437993/iphone-tcp-ip-socket-server-client-program
iphone-listen-a-tcp-port
http://stackoverflow.com/questions/10963321/iphone-listen-a-tcp-port
Question:
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.
Answer activeoldestvotes
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 is 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.