I am new to Java / Android development, and I am now trying to find my way around some network IO, specifically over sockets.
I am trying to work out the best way of achieving the functionality where I开发者_开发技巧 open a socket connection to the server, and keep it open for the server to post unsolicited data to my client. I can implement a command-response model relatively easily in a separate thread using AsyncTask.
Is there a way to do an asynchronous read on an open Socket in Android (in .Net I used Socket.BeginReceive to achieve this). Or failing that, is there a blocking socket read that I can put in a worker thread, whilst allowing the main thread to write to the same socket whilst the read is blocked?
Any advice greatly appreciated.
Socket.getInputStream().read() can be used in your AsyncTask. It blocks.
Socket.getOutpuStream().write() can be put in your main thread and will work fine if the read is blocking in another thread.
精彩评论