Network Programming: to maintain sockets or not?(网络编程:是否维护套接字?)
问题描述
我目前正在将 API 从 C# 转换为具有网络组件的 Java.
I'm currently translating an API from C# to Java which has a network component.
C# 版本似乎在其类使用期间保持输入和输出流以及套接字打开.
The C# version seems to keep the input and output streams and the socket open for the duration of its classes being used.
这对吗?
考虑到应用程序正在根据用户输入发送命令和接收事件,是否为每个消息"打开一个新的套接字流更明智?
Bearing in mind that the application is sending commands and receiving events based on user input, is it more sensible to open a new socket stream for each "message"?
我正在维护一个 ServerSocket 来监听服务器抛出的事件,但我不太确定为出站通信维护一个 Socket 和输出流是一个好主意.
I'm maintaining a ServerSocket for listening to the server throwing events but I'm not so sure that maintaining a Socket and output stream for outbound comms is such a good idea.
我不太习惯 Socket 编程.与许多开发人员一样,当我需要做网络时,我通常在应用程序层工作,而不是在套接字层工作,而我在大学做这些事情已经有 5 或 6 年了.
I'm not really used to Socket programming. As with many developers I usually work at the application layer when I need to do networking and not at the socket layer, and it's been 5 or 6 years since I did this stuff at university.
为您的帮助干杯.我想这更像是在寻求建议而不是明确的答案.
Cheers for the help. I guess this is more asking for advice than for a definitive answer.
推荐答案
在保持连接打开的成本和创建这些连接的成本之间需要权衡.
There is a trade off between the cost of keeping the connections open and the cost of creating those connections.
创建连接会耗费时间和带宽.您必须进行 3 次 TCP 握手,启动一个新的服务器线程,...
Creating connections costs time and bandwidth. You have to do the 3-way TCP handshake, launch a new server thread, ...
保持连接打开主要消耗内存和连接.网络连接是受操作系统限制的资源.如果连接的客户端过多,则可能会用完可用连接.这将消耗内存,因为您将为每个连接打开一个线程及其相关状态.
Keeping connections open costs mainly memory and connections. Network connections are a resource limited by the OS. If you have too many clients connected, you might run out of available connections. It will cost memory as you will have one thread open for each connection, with its associated state.
根据您期望的使用情况,正确的平衡会有所不同.如果您有很多客户端在短时间内连接,那么关闭连接可能会更有效.如果您长时间连接的客户端很少,您可能应该保持连接打开...
The right balanced will be different based on the usage you expect. If you have a lot of clients connecting for short period of times, it's probably gonna be more efficient to close the connections. If you have few clients connecting for long period of time, you should probably keep the connections open ...
这篇关于网络编程:是否维护套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:网络编程:是否维护套接字?
基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01