Running a socket stream in a thread - iphone

I have an application that opens a connection with 2 sockets (in and out) and I want to have them working in a thread.
The reason that I want them to be in a separate thread is that I don't want my application to freeze when I receive data, and this can happen anytime as long as the application is running.
Currently I have a class that handle also network communication and I run this class in an NSOperation, I'm not sure if it's the best solution.
I'm not very familiar with threading so guys if you could give me some help I would be very grateful.
Thanks

First, you should know that you can use the same socket to send and receive data — they're generally bi-directional. You should be able to share a reference to the same socket among multiple threads of execution.
Second, unless you'll be receiving large amounts of data and have experienced performance issues with your UI, I would delay optimizing for it. (Don't get me wrong, this is a good consideration, but premature optimization is the root of all evil, and simpler is generally better if it performs adequately.)
Third, NSOperation objects are "single-shot", meaning that once the main method completes, the operation task cannot be used again. This may or may not be conducive to your networking model. You might also look at NSThread. The fact that you already have the functionality "factored out" bodes well for your design, whatever turns out to be best.
Lastly, threading is a complex topic, but a good place to start (especially for Objective-C) is Apple's Threading Programming Guide.

Related

Is it OK to block a thread on application startup?

In my Play app, I do this in Module.configure():
bind(classOf[GadgetsReader]).toInstance(GadgetsCsvReader)
bind(classOf[Gadgets]).asEagerSingleton()
Then, I do this:
#Singleton
class Gadgets #Inject()(reader: GadgetsReader) {
val all:Seq[Gadget] = reader.readGadgets()
}
That synchronously loads a large collection of gadgets from a CSVfile into memory on startup, in a Play's rendering thread.
I did not see a similar scenario implemented anywhere in Play examples. I would like to know whether what I am doing is idiomatic Scala & Play.
Is it OK to load a very large file synchronously like this, given that I don't want any requests served until the data is fully loaded?
Is it a good thing that I created aGadgets class and then injected it, as opposed to a static/object method Gadget.all?
Should Gadget and Gadgets classes live under model?
Any other comments would be appreciated, too.
I guess it depends how large, how fast you want your startup to be, etc. In general, I'd say yes, even Akka's cluster sharding has (or at least, last I read, had) a blocking call that waits for initialisation to complete before returning. In your case it's probably fine, but one gotcha with blocking calls like this is blocking generally means doing IO, and IO can fail (eg, what if you're reading from a network filesystem, and the network fails when you're starting up?). So sometimes, it's better to design your app so that it's capable of responding (perhaps with a not available status) without the operation having being done yet, and do that operation asynchronously, with retries etc in case it fails. But perhaps this is overkill in your case.
To answer your other questions - yes, it is definitely better to dependency inject Gadgets than use a static singleton, this means you can control how Gadgets is created (perhaps you might want to initialise it differently in tests).
It's probably fine to be in the model package, but this is greatly dependent on your domain and what it looks like.

Architecture sketch for iphone stock app

I am currently trying to build a (simplified) stock app (like the one built-in on the iphone). I setup a simple server with a REST-interface which my app can communicate with.
However I am struggling to find the right/best way to build this kind of (streaming data consumer) client on the iphone.
My best bet at the moment is to use a timer to regularly pull the xml payload from the server (the connection is async but the xml parsing is not therefor the interface is blocked sometimes. I am a bit shy of thread programming since I learned some lessons the hard way on other platforms).
I read about websockets but it is not clear for me if and how they are supported on the iphone.
How would you do it?
Any hint would be appreciated, Thanks.
websockets aren't going to help you -- that's a server-side technology to make a socket-like interface work over HTTP.
If you don't want to block the GUI, you need to use another thread. You are right to be scared of doing this, so share as little as possible (preferably nothing) between the two threads. Use a message passing mechanism to get information from the background thread to the UI thread.
Take a look at ActorKit: http://landonf.bikemonkey.org/code/iphone/ActorKit_Async_Messaging.20081203.html
Take a look at this question.
It talks about asynchronous vs synchronous connections. You will want to use an asynchronous call to get your data so you don't lock up your UI. You could use that in conjunction with a polling timer to get your data from the server.
You can find more info about the NSURLConnection in apple's documentation here

CFHost DNS Resolution - When is it OK to use synchronous API?

I went to the iPhone Developer Tech Talk a few months ago and asked one of the gurus there about the lack of NSHost on the iPhone. Some code I was porting to the iPhone made significant use of NSHost throughout its networking code.
I was told that NSHost is on the iPhone, but its private. I was also told that NSHost is a synchronous API and that I shouldn't use it anyway. (If anyone could elaborate on why it shouldn't be used, as a bonus, that'd be great.)
I can see the caveats of using synchronous API's on the main thread in that they'll block until complete - and that's never a good thing with network code because there are so many factors that could cause the API to block the thread for a significant amount of time.
My solution was to write a wrapper around CFHost's asynchronous resolution functions.
The result works quite well, and I'm considering releasing it into the public domain.
But my question is this: Say my app only resolves a hostname once per run, during the connecting phase, and then cache's it for the rest of the session. During the time it is resolving, a modal screen is shown telling the user "Connecting" with a nice spinner.
Does it really matter whether or not the resolution is asynchronous?? The user has to wait to connect anyway, and the resolution is only done on the first connection. Subsequent connections use the cached result of the resolution.
When is it OK to be synchronous and when should things be asynchronous?
Your nice spinner won't spin, since the UI will get blocked as well during the synchronous call. Sure, you can make the call on a separate thread, but then you're doing essentially the same thing as the asynchronous call.

what exactly NSUrlConnection ASynchronous means?

i am getting confused what is the difference between Synchronous NSUrlConnection and ASynchronous NSUrlConnection?is there Synchronous or ASynchronous? if we use detachNewThreadSelector in connectionDidFinishLoading method,is it
ASynchronous NSUrlConnection? which is the best way?any tutorial ...
Synchronous means that you trigger your NSURLConnection request and wait for it to be done.
Asynchronous means that you can trigger the request and do other stuff while NSURLConnection downloads data.
Which is "best"?
Synchronous is very straightforward: you set it up, fire it, and wait for the data to come back. But your application sits there and does nothing until all the data is downloaded, some error occurs, or the request times out. If you're dealing with anything more than a small amount of data, your user will sit there waiting, which will not make for a good user experience.
Asynchronous requires just a little more work, but your user can do other stuff while the request does its thing, which is usually preferable. You set up some delegate methods that let you keep track of data as it comes in, which is useful for tracking download progress. This approach is probably better for most usage cases.
You can do both synchronous and asynchronous requests with NSURLConnection. Apple's documentation provides a clear explanation of the two approaches and delegate methods required for the latter approach.
It seems that you're conflating synchronous/asynchronous connections and threading. In my app I used asynchronous connections as an alternative to threading.
Let's say you want to download a big file without causing the UI to freeze. You have two basic options:
Asynchronous connection. You start with + connectionWithRequest:delegate: (or one of the other non-autorelease options) and it downloads bits of the file, calling your delegate when interesting thing happen. The runloop is still going, so your UI stays responsive. Of course you have to be careful that your delegate don't go out of scope.
Synchronous. You start the connection with + sendSynchronousRequest:returningResponse:error: but the code waits until the download is complete. You'll really need to spawn a new thread (or one of the higher level threading operations that Cocoa supports) or the UI will block.
Which option is "best" or the least painful will depend on the architecture of your application and what you're trying to achieve. If you need to create a thread for a long running process anyway, you might go with the second option. In general I would say the first option is easiest.
It's all pretty well documented on Apple's Developer site.
Something which hasn't been mentioned in the other responses is the size of the request. If you're downloading a large file, for example, then using an asynchronous connection is better. Your delegate will receive blocks of data as they arrive. In comparison, the synchronous method will wait for all the data before making it available to you. The delegate can start processing the response sooner (better user experience), or save save it to a file instead of memory (better resource usage). You also have the option to stop the response without waiting for all the data.
Basically, the asynchronous method gives you more control over the connection but at the cost of complexity. The synchronous method is much simpler, but shouldn't be used on the main UI thread because it blocks.
In response to the other answers regarding the file size: I think file size doesn't matter. If the server responds really slowly and you're loading data synchronous your UI still freezes, even if you're loading a small amount of data, like 3k.
So I'd go for the asynchronous option in every situation, cause you never know what you're going to get with regards to file size, server responsiveness or network speeds.

Online play possibilities for iPhone game?

How would you guys go about creating online play capabilities for an iPhone game? Obviously, one could poll the server every so often, but is this realistic given the capabilities of the device? Assume you're polling the server every second or two and retrieving 100 bytes of data... Is it possible to retrieve the data in the background while gameplay continues or is it going to be held up by the server poll?
Thanks in advance,
BCH
You need to make a multithreaded application. Then you can have a background thread polling the server (or better, making asynchronous requests on it.
Have a look at the NSOperation and NSOperationQueue classes. You'll make each background task be represented by an instance of an NSOperation class. This class takes care of starting the operations, making sure that they are run in the appropriate order, and accounting for any priorities that you set.
The most common way to use NSOperation is to write a custom subclass and override the method, main. The main method gets called to perform the operation when the NSOperationQueue schedules it to run.
If you don't want the overhead of subclassing, take a look at the NSInvocationOperation class. This is a concrete subclass of NSOperation that makes it easy to attach an operation to an existing method. NSInvocationOperation objects can be added to an NSOperationQueue (just like NSOperations), so that you get multi-threading without having to subclass.
You can do asynchromous requests. But you are asking a really, really hard question here. Just want to make sure you know that.
Take a look at the WiTap example (in xcode do a full text search for witap). It uses NSStreams to get asynchronous behavior without you having to resort to managing your own threads or poll.
Use OpenFeint.. It allows you to develop Over the internet worldwide non real time turn based multiplayer games easily..
I'm not sure if GameCenter now supports similar functions.