网络编程:是否维护套接字? [英] Network Programming: to maintain sockets or not?

查看:20
本文介绍了网络编程:是否维护套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将 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 ...

这篇关于网络编程:是否维护套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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