使用ObjectInputStream从套接字检查可用的对象 [英] Checking for an available Object from Socket using ObjectInputStream

查看:85
本文介绍了使用ObjectInputStream从套接字检查可用的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ServerClient使用字符串进行通信(使用BufferedReaderPrintWriter类)时,BufferedReader类具有称为ready()的方法,这意味着有一个字符串在等待客户端抓取和处理.这种方法还使服务器由2个线程组成,这是我想要实现的.

When Server and Client are communicating using Strings (using BufferedReader and PrintWriter classes), the BufferedReader class has a method called ready(), meaning that there is a string waiting for the client to grab and process. This method also makes the server to be made with 2 threads, which is what I want to achieve.

使用ObjectInputStreamObjectOutputStream类时,OIS类没有'ready()'方法,而是具有名为'available()'的方法,该方法返回要被使用的字节数.处理.问题是available()方法每次都返回0,并且OIS中缺少'ready()'方法使服务器成为多线程(每个连接加主线程1个线程),而这不是我想要的.

When using ObjectInputStream and ObjectOutputStream classes, OIS class doesn't have a 'ready()' method, instead it has a method called 'available()' which returns the number of available bytes to be processed. The problem is that the available() method returns 0 every time and the lack of 'ready()' method in OIS makes the Server to be multi-threaded (1 thread for each connection plus main thread) and that's not what I want.

因此,有没有办法检查Server是否已通过SocketObjectInputStream接收到ObjectInputStream,而又没有为每个连接创建和保存Thread?

So, is there a way to check whether a Server has "received" an Object from the ObjectInputStream over the Socket without creating and holding a Thread for every connection?

推荐答案

是否有一种方法可以检查服务器是否通过套接字从ObjectInputStream接收"了一个对象,而没有为每个连接创建并持有线程?

is there a way to check whether a Server has "received" an Object from the ObjectInputStream over the Socket without creating and holding a Thread for every connection?

否,因为服务器 尚未通过SocketObjectInputStream接收到Object. 直到您调用readObject().都不会这样做ObjectInputStream.available()始终返回零的原因是它不预先知道下一个对象的大小,因此无法确定是否它是否全部存在,所以它不是对您的谎言,它只是说您很可能在没有阻止的情况下无法读取任何内容.对此没有解决方案. Selector.select()不再是解决方案,因为它也不知道下一个对象的大小,更不用说在select()所需的非阻塞模式和

No, because the server hasn't 'received an Object from the ObjectInputStream over the Socket'. It doesn't do that until you call readObject(). The reason ObjectInputStream.available() always returns zero is that it doesn't know in advance how large the next object is, so it can't tell whether it's all there or not, so it doesn't lie to you, it just says you probably can't read anything without blocking. There is no solution to this. Selector.select() isn't any more of a solution because it also doesn't know how large the next object is, not to mention the difficulty of switching between the non-blocking mode required for select() and the blocking mode required for readObject().

使用专用的读取线程.

这篇关于使用ObjectInputStream从套接字检查可用的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆