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.
To find what is listening on a TCP/IP port, open a terminal and go to a shell command-line, and use lsof , a command that LiSts Open Files (TCP ports are considered a type of file in UNIX).
Yes, you can use the same port number for both TCP and UDP. Many protocols already do this, for example DNS works on udp/53 and tcp/53.
Listen Port - serves as an endpoint in an operating system for many types of communication. It is not a hardware device, but a logical construct that identifies a service or process. As an example, an HTTP server listens on port 80. A port number is unique to a process on a device.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With