阻塞案例
阻塞案例,由于单线程,同一时间只有一个TCP链接能够被处理。
int main() {
int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //AF_INT:ipv4, SOCK_STREAM:tcp协议
//将套接字和IP、端口绑定
struct sockaddr_in *serv_addr = malloc(sizeof(struct sockaddr_in));
serv_addr->sin_family = AF_INET; //使用IPv4地址
serv_addr->sin_addr.s_addr = inet_addr("127.0.0.1"); //具体的IP地址
serv_addr->sin_port = htons(11234); //端口
int on = 1;
if (setsockopt(serv_sock, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on)) == -1) {
printf("处理失败SO_REUSEPORT失败");
exit(1);
}
bind(serv_sock, (struct sockaddr *) serv_addr, sizeof(struct sockaddr));
listen(serv_sock, 20);
for (;;) {
int fd = accept(serv_sock, NULL, NULL);
char *hello = "hello chenshun!";
char cc[20];
ssize_t rr = read(fd, cc, 10);
if (rr == -1) {
close(fd);
}
printf("i receive your message:%s\n", cc);
write(fd, hello, strlen(hello));
write(fd, "good bye!", strlen("good bye!"));
close(fd);
}
return 0;
}