问题描述
- 网络编程新手求指导---客户端为何write()始终返回0
-
在本机上做实验,客户端输入文字在服务器端显示客户端
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <sys/types.h> #include <unistd.h> #define portnumber 3333 int main(int argc, char *argv[]) { int sockfd, nwrite=0; char buffer[1024]; struct sockaddr_in server_addr; struct hostent *host; /*检查输入格式*/ if(argc != 2) { fprintf(stderr,"Usage: %s hostnamen",argv[0]); exit(1); } /*使用hostbyname获取host名字*/ if((host = gethostbyname(argv[1])) == NULL) { fprintf(stderr,"gethostname error!n"); exit(1); } /*建立socket描述符*/ if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1) { fprintf(stderr,"Socket error!n"); exit(1); } /*客户程序填充服务器端资料*/ bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(portnumber); server_addr.sin_addr = *((struct in_addr *)host->h_addr); /*客户端发起连接*/ if(connect(sockfd,(struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1) { fprintf(stderr,"fail to connect!%sn", strerror(errno)); exit(1); } /*链接成功*/ printf("Please input char:n"); /*发送数据*/ fgets(buffer,1024,stdin); printf("%s", buffer); if((nwrite = write(sockfd,buffer,strlen(buffer)) == -1)) { printf("write error!n"); } printf("nwrite = %dn", nwrite);//为何一直返回0 ?写不进去? /*关闭连接*/ close(sockfd); exit(0); }
服务器端
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <netdb.h> #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #define portnumber 3333 int main(int argc, char *argv[]) { int sockfd; int nbytes; int sin_size; int new_fd; char buffer[1024]; struct sockaddr_in server_addr; struct sockaddr_in client_addr; /*服务端创建套接字*/ if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1) { fprintf(stderr, "Create socket error!n"); exit(1); } /*结构清零*/ bzero(&server_addr, sizeof(struct sockaddr_in)); { server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(portnumber); } /*绑定结构*/ if(bind(sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1) { fprintf(stderr, "Bind error! %sn", strerror(errno)); exit(1); } /*监听套接口设置最大监听个数*/ if(listen(sockfd,5) == -1) { fprintf(stderr, "listen setting error!n"); exit(1); } while(1) { sin_size = sizeof(struct sockaddr_in); if(new_fd = accept(sockfd, (struct sockaddr *)(&client_addr), &sin_size) == -1) { fprintf(stderr, "accept error!n"); exit(1); } /*与客户端连接成功*/ fprintf(stderr, "Server get connction from %sn", inet_ntoa(client_addr.sin_addr)); if((nbytes = read(new_fd, buffer, 1024)) == -1) { fprintf(stderr, "read error!n"); exit(1); } buffer[nbytes] = ''; printf("Received from client %s : %s", inet_ntoa(client_addr.sin_addr), buffer); close(new_fd); } close(sockfd); exit(0); }
解决方案
括号那里改一下试试 nwrite = write(sockfd,buffer,strlen(buffer));
if( ..... )
......
时间: 2024-12-31 19:12:52