使用一个套接字创建2个流 [英] Creating 2 streams with one socket

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

问题描述

我正在尝试创建一个在互联网上运行的多人游戏。问题是我试图在流上输入,由于某种原因我不能用一个套接字制作2个流,我会解释:

I'm trying to create a multiplayer game, who runs on the internet. The problem is that I'm trying to get input on a stream and for some reason I can't make 2 streams with one socket, and I'll explain:

Socket s=new Socket("127.0.0.1",5001);
ObjectInputStream obj1=new ObjectInputStream(s.getInputStream());
ObjectInputStream obj2=new ObjectInputStream(s.getInputStream());

有人可以解释一下为什么这段代码不起作用吗?

Can someone explain me why this code snippet isn't working?

编辑:这是代码示例无法正常工作的另一个示例。

Here's another example for code sample that isn't working.

while (true) {
    try {
        objI = new ObjectInputStream(sock.getInputStream());
        objO = new ObjectOutputStream(sock.getOutputStream());
     }catch(Exception e) {
        e.printStackTrace();
     }
}

编辑2:非常感谢您的回答。我试图刷新对象,但我一直收到此错误:

Edit 2: thanks very much for answering. I tried to flush the objects, but I keep getting this error:

java.io.StreamCorruptedException: invalid stream header: 33740003
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Proccess.run(Proccess.java:22)
at java.lang.Thread.run(Unknown Source)


推荐答案

Streams是有状态的 - 当您从流中读取时,您正在从流中的某个位置读取,并通过这样做来更改位置。

Streams are stateful - when you read from a stream, you are reading from some position in the stream, and by doing that you change the position.

如果有两件事(比如你是两个包装器ObjectInputStreams)同时从底层流中读取它们,它们都会尝试改变流中的位置,但是没有人知道对方在做什么。因此,从一个人那里读取会改变位置,然后另一个人希望流在它离开的位置,但事实并非如此。

If two things (like you're two wrapper ObjectInputStreams) are reading from the underlying stream at the same time, they will both try to change the position within the stream, but neither one knows what the other is doing. So reading from one changes the position, and then the other one expects the stream to be where it left it, but it is not.

想象一下你得到的答案是写在单独的纸上的文字,一个接一个地给你。但是当你正在阅读那些纸张时,其他人会在你看到它们之前把它们带走一些 - 你得到的东西没有意义。这就是发生的事情 - 一个流占用了部分数据,当另一个流再次查看数据时,其中一些流丢失,被其他流消耗。

Imagine you were getting this answer as words written on separate pieces of paper, being given to you one-by-one. But while you are reading the pieces of paper, somebody else is taking some of them away before you have seen them - what you got would not make sense. That is what is happening - one stream takes away parts of the data, and when the other stream looks at the data again, some of it is missing, consumed by the other stream.

一个 ObjectInputStream读取传入的对象。如果要将这些对象发布到多个使用者,请创建一组事物以将传入的对象发送到,并迭代它们并将新对象传递给每个对象。

Have one ObjectInputStream that reads incoming objects. If you want to publish those objects to multiple consumers, create a collection of things to send the incoming objects to, and iterate over them and pass the new object to each one.

这篇关于使用一个套接字创建2个流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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