Should I use java.io or java.nio for my network client implementation?
So I'm creating a game, very basic multiplayer. I've got the server side down using asynchronous non-blocking I/O (raw java.nio
) but now I need to design the client.
I'm not sure how I should do this. My gut tells me using NIO for a client is overkill (it's not like it's going to handle multiple connections, right?) but I want a second opinion.
So th开发者_StackOverflowe question is, for a single-connection client, is the best option to use java.io
, or java.nio
?
And, if the best option is standard I/O, is it still good practice to use ByteBuffer
s? Or just the usual byte arrays?
Performance may vary, but it is platform dependant and most likely insignificant. For example, tests I've done have shown that NIO and standard I/O perform differently on Linux and Windows. When sending large amounts of data, NIO performed better on the Linux platform, but it was the opposite on Windows. Note: I had configured sockets to be blocking on NIO. When writing a client application, there is little reason to be using non-blocking I/O and polling.
I would not worry about performance. It is hard to say which is better in that sense. Go with what you are comfortable with. If you want to use standard I/O, but still would like to use ByteBuffers, what you can do is wrap the InputStream
and OutputStream
of the Socket using newChannel(InputStream) and newChannel(OutputStream), respectively. However, there is overhead from additional synchronization and other checks. My advice is to use java.nio
and use blocking I/O (configureBlocking(true)
).
Simple Stream I/O is a lot easier to handle, and not necessarily slower. It internally uses NIO, for the network accesses, too, I think. (Of course, if you can simply reuse your server's code, using it might be an option.)
As OutputStream does not support writing a ByteBuffer, there is no point in using it here.
(Disclaimer: This is just my opinion (and experience from trying to port my stream IO based networking package to NIO). I'm not sure about best practice here.)
精彩评论