不过这个程序是存在一些问题的,虽然情况下都能运行,不过对异常情况没有任何抵抗力
1、client_sockfd未关闭
2、%s输出方式,如果收到的字符串不包含\0等特殊情况?
3、server为所有client服务,如果一个client端出错或者关闭,则关闭server,逻辑处理失当
修改while部分如下:
while (1) { memset(recvbuf, 0, BUFFERSIZE); printf("server is waiting\n"); //Accept a connection, accept will block here, //so ,there's no need to sleep in this loop like in udp client_sockfd = accept(server_sockfd, (struct sockaddr*)&client_address, &addr_len); //recv message from client recvrecv_len = recv(client_sockfd, recvbuf, BUFFERSIZE-1, 0); if (-1 == recv_len) { //error while recv perror("recv"); close(client_sockfd); continue; } else if (0 == recv_len) { //peer closed the socket close(client_sockfd); continue; } recvbuf[recv_len] = '\0'; printf("server receieve : %s\n", recvbuf); printf("server port : %d\n", ntohs(server_address.sin_port)); printf("client port : %d\n", ntohs(client_address.sin_port)); printf("client addr : %s\n", inet_ntoa(client_address.sin_addr)); sleep(3); //send to client via client_sockfd result = send(client_sockfd, recvbuf, recv_len, 0); if (result != result) { perror("send"); close(client_sockfd); continue; } close(client_sockfd); }