开发者

AsyncSocket Delay

开发者 https://www.devze.com 2023-01-04 21:47 出处:网络
So I\'m writing an application for my iphone that networks to my computer running a java application using AsyncSocket. On the java side, it should print out \"Ok\" when the iPhone connects to the ser

So I'm writing an application for my iphone that networks to my computer running a java application using AsyncSocket. On the java side, it should print out "Ok" when the iPhone connects to the server. I also added a sleep() command to the iphone side, so after it connects to the server, it sends some data and then sleeps for 5 seconds. But, on the java side, all of the data, including the "Ok" and the data gets printed out AFTER the sleep command. So its like the iphone isn't connecting until after the program execution is over. Can someo开发者_高级运维ne please help me? Thanks...


AsyncSocket is meant to be fire and forget. You are not supposed to wait for anything to happen. The whole purpose of this class is to do its thing in the background and then notify you when it is done.
If you need a blocking socket then you should use something else.


The reason you're seeing this problem is because AsyncSocket executes asynchronously on the runloop, but when you call sleep() you are blocking the runloop that AsyncSocket is trying to execute on.

When you call [asyncSocket connectToHost:...], the method returns immediately and the connection attempt continues in the background. The delegate method will notify you of when the connection is established. But the code that finishes setting up the connection (within AsyncSocket) must also run on the runloop.

Similarly, when you call [asyncSocket writeData:...], the method returns immediately. The code that sends this data gets scheduled to run on the socket's runloop. But if you call sleep() you prevent that code from running.

0

精彩评论

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