long polling in objective-C

前端 未结 2 1374
心在旅途
心在旅途 2020-11-30 22:25

I have an application that uses an API to get real time updates on the website. They use what they call a long-polling technique:

Long polling is a v

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 22:36

    Long polling is making a read request to a server, the server gets the requests, finds that there's nothing of interest to send you, and rather than returning nothing, or "empty", it instead holds on to the request until something interesting shows up. Once it finds something, it writes to the socket and the client receives the data.

    The detail is that for this entire time, using generic socket programming, the client is blocked and hanging on the sockets read call.

    There are two ways to deal with this (well, three if you don't mind being stuck on the main thread for several seconds, but let's not count that one).

    1. Put the socket handling code in a thread. In this case, the entire socket process is in an independent thread within the program, so it happily sits stuck on the read waiting for a response.

    2. Use asynchronous socket handling. In this case, your socket read does NOT block the main thread. Instead, you pass in call back functions that respond to the activity on the socket, and then go about your merry way. On the Mac, there's CFSocket which exposes this kind of functionality. It spawns its own thread, and manages the socket connection using select(2).

    This is a nice little post talking about CFSocket.

    CFSocket fits well in to the Mac idiom of message passing and eventing, and is probably what you should be looking at for doing this kind of work. There is also an Obj-C class wrapper built on CFSocket called ULNetSocket (formerly NetSocket).

提交回复
热议问题