Java服务器:为每个收到的数据包启动一个新线程? [英] java server: start a new thread for each received packet?

查看:100
本文介绍了Java服务器:为每个收到的数据包启动一个新线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习如何在Java中对TCP服务器进行编程.我正在为新的每个客户端连接(多线程服务器)创建一个新线程.

I am currently learning how to program a tcp server in java. I am creating a new thread for new each client connection (multithreaded server).

客户端连接到服务器后,我想将数据从客户端发送到服务器.在服务器端,服务器处于while循环中,从套接字inputstream读取数据.我现在要问:我应该为每个收到的数据包创建一个新线程吗?

After the client connects to the server, I want to send data from the client to the server. On serverside the server is in a while loop reading data from the sockets inputstream. I want to ask now: Should I create a new thread for each received packet?

例如,客户端发送字符串"Hello".服务器应该在新线程中处理此数据包以便继续读取,因为我认为如果不创建新线程,服务器将不会继续读取数据,并且如果客户端在"Hello"数据包之后发送另一个数据包例如再见",服务器可能无法读取它,因为它可能仍在忙于处理"Hello"数据包.

For example the client sends the string "Hello". Should the server handle this packet in a new thread so it can continue reading, because I think if I don't create a new thread, server doesn't go back on reading and if client sends another packet after the "Hello" packet for example "Bye", the server might not read it because it could still be busy handling the "Hello" packet.

为了清楚起见,我不是在谈论服务器套接字接受方法,而是在谈论套接字输入流中的数据.

To be clear I am not talking about serversockets accept method, I am talking about the data from sockets inputstream.

请对此给予启发.

推荐答案

如果您的数据包处理任务不是很繁重(可能不是很繁重),则您不应该这样做.线程将处理一条消息,然后返回接收新消息.不会丢失任何数据-如果没有人从输入流中读取数据,则数据传输将保持有效(在所有缓冲区填满之后). 只需为每个客户端保留一个线程,在大多数情况下就足够了.

If your packet handle task is not very heavy (probably it is not), you shouldn't. Thread will handle a message and come back to receiving new messages. No data will be lost - if nobody reads from inputstream, data transfer just holds (after all buffers filled). Just keep one thread per client, it is enough in most cases.

这篇关于Java服务器:为每个收到的数据包启动一个新线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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