TCP API是全双工的 . 这意味着TCP API允许同时从连接的两端发送数据 . 让我们看一下来源证明:
#include
#include
#include
#include
#include
#include
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上)是:
父母:写完了好
孩子:写得好
孩子:收到'你好!' 6B
孩子:写得好
父母:收到'你好!你好!' 12B
父母:写完了好
孩子:收到'你好!' 6B
父母:没有可用数据
因此TCP API是全双工的,并且可以同时从两侧发送数据 . 我认为实现也是全双工,但它需要编写更复杂的测试来识别 . 这当然取决于实现 . 当至少一个传输链路不是全双工时,良好的实现可能不会产生影响 .