【发布时间】:2015-08-18 07:44:11
【问题描述】:
我正在使用简单的锁定 TCP 套接字向远程服务器发送消息,但我遇到的问题是,对于每条消息,发送它所花费的时间非常不同。
这是我得到的(一些例子):
Bytes Sent: 217, Time: 34.3336 usec
Bytes Sent: 217, Time: 9.9107 usec
Bytes Sent: 226, Time: 20.1754 usec
Bytes Sent: 226, Time: 38.2271 usec
Bytes Sent: 217, Time: 33.6257 usec
Bytes Sent: 217, Time: 12.7424 usec
Bytes Sent: 217, Time: 21.5912 usec
Bytes Sent: 217, Time: 31.1480 usec
Bytes Sent: 218, Time: 28.3164 usec
Bytes Sent: 218, Time: 13.0963 usec
Bytes Sent: 218, Time: 82.8254 usec
Bytes Sent: 218, Time: 13.0963 usec
Bytes Sent: 227, Time: 30.7941 usec
Bytes Sent: 218, Time: 27.9624 usec
Bytes Sent: 216, Time: 2.1237 usec
Bytes Sent: 218, Time: 12.3884 usec
Bytes Sent: 227, Time: 31.1480 usec
Bytes Sent: 227, Time: 88.4887 usec
Bytes Sent: 218, Time: 93.0901 usec
Bytes Sent: 218, Time: 7.7870 usec
Bytes Sent: 218, Time: 28.3164 usec
Bytes Sent: 227, Time: 89.5505 usec
Bytes Sent: 218, Time: 84.2412 usec
Bytes Sent: 218, Time: 13.8042 usec
Bytes Sent: 227, Time: 99.4612 usec
Bytes Sent: 218, Time: 86.0110 usec
Bytes Sent: 218, Time: 12.3884 usec
Bytes Sent: 218, Time: 87.7807 usec
Bytes Sent: 216, Time: 3.5395 usec
Bytes Sent: 218, Time: 4.6014 usec
Bytes Sent: 218, Time: 36.1034 usec
Bytes Sent: 218, Time: 14.8661 usec
Bytes Sent: 218, Time: 24.0689 usec
Bytes Sent: 218, Time: 18.0517 usec
Bytes Sent: 227, Time: 24.4229 usec
有人知道为什么会发生这种情况吗?为什么一条消息需要 3 微秒才能发送,而其他消息需要 80 微秒?
有没有办法解决这个问题?
注意:我要归档的主要目标是尽可能快地发送每条消息。我不需要任何同步套接字,至少在它们工作得更快之前是这样。
关于我的工作的一些额外细节:
C++,Visual Studio 2013
我如何打开:
...
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
...
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
...
我如何发送和计算时间:
...
LARGE_INTEGER cT;
QueryPerformanceCounter(&cT);
long long dT = cT.QuadPart;
iBytesSent = send(ConnectSocket, msgFinal, msgFinalLen, 0);
QueryPerformanceCounter(&cT);
dT = cT.QuadPart - dT;
...
另外我正在从其他线程监听这个套接字,我不知道这是否会影响发送:
iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFLEN, 0);
【问题讨论】:
-
TCP 是一种流协议。它没有“消息”的概念,您正在发送一个字节流。这意味着,例如,接收方可能会以不同大小的块接收数据,而不是您发送的数据。 TCP 只保证,另一端以相同的顺序接收相同的字节,没有任何丢失(或者如果重新发送失败则断开连接)。
-
我不认为你在测量发送时间,你只是在测量
send通话时间。 -
如果您希望消息尽快发送出去,也可以设置 TCP_NODELAY。 msdn.microsoft.com/en-us/library/windows/desktop/…
-
@dau_sama 除了这实际上会使发送过程变慢。
send操作在发送数据包时比不发送数据包时花费更长的时间。设置 TCP_NODELAY 将使每个发送操作发送一个数据包。
标签: c++ sockets raw-sockets