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

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

问题描述

我目前正在将API从C#转换为具有网络组件的Java.

I'm currently translating an API from C# to Java which has a network component.

在使用C#版本的类期间,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.

创建连接需要花费时间和带宽.您必须进行三向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天全站免登陆