这是一个更大的开销:每次创建一个新的套接字或维护一个用于数据传输的套接字 [英] Which is a larger overhead: Creating a new socket each time or maintaining a single socket for data transfer

查看:48
本文介绍了这是一个更大的开销:每次创建一个新的套接字或维护一个用于数据传输的套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用套接字发送数据的最佳方法是:

Which is the best method for sending a data using sockets:

方法一:每次需要发送数据时创建一个新的socket,传输完成后关闭.

Method 1: Creating a new socket every time when data needs to be sent and closing it when the transfer is complete.

方法二:使用同一个socket,而不是创建一个新的socket,即使在等待新数据时也保持连接.

Method 2: Using the same socket instead of creating a new socket and maintaining the connection even when waiting for new data.

推荐答案

这取决于套接字的类型,但在通常情况下,除非资源非常有限,否则最好保留套接字.

It depends on the kind of socket, but in the usual cases it is better to keep the socket unless you have very limited resources.

  • UDP 是无连接的,即您创建套接字并且在发送数据包时没有由于连接设置而导致的延迟.但是仍然涉及系统调用和内存分配等,所以它便宜但不是免费的.
  • TCP 需要先建立连接,然后才能开始发送数据.完成的速度取决于延迟,即在本地机器上快,在本地网络上更慢,在互联网上更慢.此外,连接启动缓慢,因为尚不知道可用带宽.
  • 在 TCP 连接设置之上使用 SSL/TLS 会更加昂贵,因为它需要在客户端和服务器之间进行更多的往返.

总而言之:如果您使用 TCP,您几乎总是最好保持套接字打开并仅在您缺乏保持其打开所需的资源时才关闭它.一个很好的折衷方法是只要套接字上有足够的活动就关闭套接字.这是通常使用 HTTP 持久连接完成的方法.

In summary: If you are using TCP you almost always better keep the socket open and close it only if you lack the necessary resources to keep it open. A good compromise is to close the socket as long as you have enough activity on the socket. This is the approach usually done with HTTP persistent connections.

这篇关于这是一个更大的开销:每次创建一个新的套接字或维护一个用于数据传输的套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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