TCP API 是全双工的。这意味着 TCP API 允许同时从连接的两端发送数据。让我们看看测试程序的来源来证明:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
void do_write(const char* who, int socket) {
const char hello[] = "hello!";
if( 0 < write(socket, hello, strlen(hello)) )
printf( "%s: write done ok\n", who );
else
printf( "%s: write error: %s\n", who, strerror(errno) );
}
void do_read(const char* who, int socket) {
/* do parental things with this end, like reading the child's message */
char buf[1024];
int n = read(socket, buf, sizeof(buf));
if( 0 < n )
printf("%s: received '%.*s' %db\n", who, n, buf, n);
else if( 0 == n )
printf( "%s: no data available\n", who );
else
printf( "%s: read error: %s\n", who, strerror(errno) );
}
int main() {
int fd[2];
static const int parent = 0;
static const int child = 1;
pid_t pid;
socketpair(PF_LOCAL, SOCK_STREAM, 0, fd);
pid = fork();
if (pid == 0) { /* child process */
close(fd[parent]);
do_write("child", fd[child]);
do_read("child", fd[child]);
/* sleep(1); */
do_write("child", fd[child]);
do_read("child", fd[child]);
} else { /* parent process */
close(fd[child]);
do_write("parent", fd[parent]);
do_read("parent", fd[parent]);
do_write("parent", fd[parent]);
do_read("parent", fd[parent]);
}
return 0;
}
输出(在 FreeBSD 上)是:
parent: write done ok
child: write done ok
child: received 'hello!' 6b
child: write done ok
parent: received 'hello!hello!' 12b
parent: write done ok
child: received 'hello!' 6b
parent: no data available
所以 TCP API 是全双工的,数据可以同时从双方发送。我认为实现也是全双工的,但它需要编写更复杂的测试来识别。当然,这取决于实现。当至少一个传输链链路不是全双工时,良好的实施可能不会产生影响。