因此,我向客户端写了一个对象,如下所示:
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.writeObject(args);
out.close();
并在客户端接收对象,如下所示:
ObjectInputStream in = new ObjectInputStream(connection.getInputStream());
Object objIn;
while(true) {
if((objIn = in.readObject()) != null) {
//work with obj
}
}
我从不在客户端创建输出流,也从不在服务器端创建输入流。
而且,我发送的对象是可序列化的。
谢谢你的帮助!
编辑:这个问题的“重复”并不能帮助我回答我的问题,所以这个问题不是重复的。
发布于 2015-09-29 20:16:03
while(true) {
if((objIn = in.readObject()) != null) {
//work with obj
}
}
问:你为什么要测试null
?你打算发送null
吗?因为那是你唯一的一次机会。答:因为您认为readObject()
在流结束时返回null
。虽然您忽略了将避开无限循环的break
。
没有。它抛出EOFException.
,所以循环应该如下所示:
try
{
while(true) {
objIn = in.readObject();
//work with obj
}
}
catch (EOFException exc)
{
// end of stream
}
finally
{
in.close();
}
发布于 2015-09-29 20:40:43
假设您在从connection对象读取输入流时收到了异常。
如果您已经在上面引用的输入流代码之前调用了connection.getInputStream()
,那么您将收到EOF异常。因为连接对象中的输入流已经被消耗了。
解决此类问题的一个解决方案是在随机访问文件中写入输入流的内容,因为它们使您能够遍历该文件。
public static RandomAccessFile toRandomAccessFile(InputStream is, File tempFile) throws IOException
{
RandomAccessFile raf = new RandomAccessFile(tempFile, "rwd");
byte[] buffer = new byte[2048];
int tmp = 0;
while ((tmp = is.read(buffer)) != -1)
{
raf.write(buffer, 0, tmp);
}
raf.seek(0);
return raf;
}
稍后,您可以从文件中读取,如下所示。
public static InputStream toInputStream(RandomAccessFile file) throws IOException
{
file.seek(0); /// read from the start of the file
InputStream inputStream = Channels.newInputStream(file.getChannel());
return inputStream;
}
https://stackoverflow.com/questions/32856827
复制相似问题