开发者

How to use sockets in iOS?

开发者 https://www.devze.com 2023-01-26 11:10 出处:网络
I have to implement an iOS application, which connects to a web server and receives events from it, i.e. server long polling. I plan to use the AsyncSocket library.

I have to implement an iOS application, which connects to a web server and receives events from it, i.e. server long polling. I plan to use the AsyncSocket library.

My idea is to open a socket on the iPhone, send it to the server the first time I connect to it, and then listen infinitely to the socket and update the GUI accordingly开发者_JAVA技巧 to the events the server sends to it. Here are my questions:

  1. Is this a correct approach and if not - how it should be done?
  2. Can the server send data to the socket I give to it (as long as the socket is opened), if the iPhone and the server are on different networks, and the iPhone is on a local network?


  1. Yes. 2. Yes.

On the fone, you will get information arriving in to the fone probably something like this:

-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData*)data withTag:(long)tag
    {
    [data getBytes:&getMe length:sizeof(CommProt)];
    // do not forget to roll in the next read...
    [sock readDataToLength:sizeof(CommProt) withTimeout:-1 tag:0];
    // now parse that command
    }

and on the fone you will send information from the fone quite likely something like this (there are a couple of different approaches)...

-(void) mySendStringData:(NSString *)sss
    {   
    // so easy, thank goodness for AysncSocket
    NSData* data = [sss dataUsingEncoding: NSASCIIStringEncoding];

    [theSocket writeData:data withTimeout:0.5 tag:0];
    [theSocket writeData:quickCR withTimeout:0.5 tag:0];
    // (in the protocol at hand, we are using a delimiter on the end (a CR))
    }

Note. It is possible this post i made could be helpful to you: it gives the lowdown on protocols in iOS:

Tablet(iPad/Android)-Server Communication Protocol

I hope it helps.

Conceivably this could help iPad and Arduino Integration and this secret knowledge could help Client/Server GKSessions Cheers

0

精彩评论

暂无评论...
验证码 换一张
取 消