[英]Writing and Reading Objects over Java NIO non blocking SocketChannels
I am new to Socket programming, and I am trying to write a simple chat application.My server utilizes a HashSet of Strings to store user name information and I want to pass the HashSet
from the server to the client. 我是Socket编程的新手,我正在尝试编写一个简单的聊天应用程序。我的服务器使用字符串的HashSet存储用户名信息,并且我希望将
HashSet
从服务器传递给客户端。 I was able to do this before with ObjectOutputStream
and ObjectInputStream
over regular Sockets. 以前,我可以通过普通套接字在
ObjectOutputStream
和ObjectInputStream
上执行此操作。 However, now I am using SocketChannel
and it does not allow this I get the following exception: 但是,现在我正在使用
SocketChannel
,但不允许这样做,我得到以下异常:
java.nio.channels.IllegalBlockingModeException
So i searched the web on how to do this and everyone says something different, and most go way over my head. 因此,我在网络上搜索了如何执行此操作,每个人都说了些不同的话,而大多数人的想法都超出了我的脑海。 Is there a simple way to do this without completely overriding the
writeObject
and readObject
methods myself? 是否有一种简单的方法可以完成此操作,而无需自己完全重写
writeObject
和readObject
方法?
Thank You in advance. 先感谢您。
I recommend you either don't use non-blocking mode or don't use serialization. 我建议您要么不使用非阻塞模式,要么不使用序列化。
If you must, you need to serialize to a ByteArrayOutputStream
, get the length, send the length, send the bytes, receive the length, keep reading, accumulating data until you have the correct length of data, put it into a ByteArrayInputStream
, and deserialize from that. 如果必须,您需要序列化为
ByteArrayOutputStream
,获取长度,发送长度,发送字节,接收长度,继续读取,累积数据,直到数据长度正确为止,将其放入ByteArrayInputStream
并反序列化从那开始。 Not easy, especially the hand-waving around 'keep reading'. 这并不容易,尤其是挥舞着“保持阅读”。 And it wastes both time and space.
而且浪费时间和空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.