Socket 的 dataInputStream 是否知道如何处理对其进行多次写入?

发布于 2024-12-10 04:19:27 字数 564 浏览 0 评论 0原文

我正在开发一个网络游戏,一般来说:

我有一个服务器,它为每个连接到它的客户端启动一个服务器线程。
其目的是监听来自特定客户端的消息并在服务器上处理它。
此外,对于每个打开的客户端,它都会启动一个 clientThread,它是来自服务器的消息的侦听线程。
这两个线程非常简单且相似,它们实现了 Runnable 接口,因此重写了 run 方法。
每个 Run 方法都是某种无限循环,在其启动时具有命令(阻塞命令):

int command = m_In.readInt();

然后通过切换案例结构对接收到的命令进行处理。
处理完成后,循环导致代码返回到阻塞 m_In.readInt()
等待另一个命令的到来。

我的问题是:我的网络游戏有足够的选项使用 m_In 上的通信,所以如果有两条或更多条消息几乎一起到达 clientThread,会发生什么情况,dataInputStream 将如何起作用?
它会开始处理第一条消息,并在完成后获取某种队列上的第二条消息吗?或者它可能会丢弃第二条消息并且它会丢失? 也许该流有缓冲区,因此它将第二条消息存储在队列或其他东西中?

谢谢

I am developing a Net game, in general:

I have a server which launch a serverThread for each client that has connected to it.
Its purpose is to listen to messages from the specific client and to process it on the server.
Also for each client that is opened it launch a clientThread which is a listening thread to messages from the server.
The two threads are quite simple and similar threads which implements the Runnable Interface and therefore override the run method.
Each Run method is some kind of infinite loop that has on its start the command (blocking command):

int command = m_In.readInt();

and then do a process by switch cases structure over the received command.
after process was done, the loop cause the code to return to the blocking m_In.readInt()
To wait for another command to come.

My question is: My Net game has enough options which are using the communication over this m_In, so what happens if there are two messages or more coming almost together to the clientThread, how would the dataInputStream will act?
Will it begin to process first message and after its done will grab the second which is on some kind of a queue? or it could drop the second message and it will be lost?
Maybe that stream has buffer so it stores the second message in a queue or something?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

独留℉清风醉 2024-12-17 04:19:27

流本质上期望数据以指定的顺序出现。如果有两个线程同时写入同一个流,就会发生不好的事情。

现在,您当然可以同步对流的访问,并使两个线程交错写入(只要您在流上构建某种格式来告诉接收者如何读取数据),但默认情况下您不会这样做。

但通常情况下,每个客户端线程都有自己的连接,因此有自己的要写入的流。显然,服务器可以“同时”从多个流中读取数据,这是正常的服务器模式。

Streams by their nature expect data to come in a specified order. If you have two threads writing to the same stream at the same time, bad things will happen.

Now you can certainly synchronize access to the stream and have the two thread interleave their writing (so long as you build some sort of formatting on the stream that tells the receiver how to read data), but you don't get this by default.

Typically though, each client thread would have their own connection and thus their own stream to write into. A server can obviously read from multiple streams at the 'same time', and that is the normal server pattern.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文