java全双工_TCP双向还是全双工?

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是全双工的,并且可以同时从两侧发送数据 . 我认为实现也是全双工,但它需要编写更复杂的测试来识别 . 这当然取决于实现 . 当至少一个传输链路不是全双工时,良好的实现可能不会产生影响 .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值