LINUX网络编程TCP服务器 客户端 有乱码怎么解决?

TCP客户端代码如下:#include <stdio.h>#include <stdlib.h>#include <string.h> /*bzero library */#include <sys/socket.h> /* socket functions */#include <netinet/in.h> /* socket structs */#include <arpa/inet.h> /* inet_ptoa functions */#define SA struct sockaddrint main(int argc, char **argv){ int socketfd,n,clilen; struct sockaddr_in server; char buff[1024]; if(argc<2) { printf("usage:a.out IP port\n"); exit(0); } if((socketfd = socket(AF_INET,SOCK_STREAM,0))<0) { printf("socket creation error...\n"); exit(0); } bzero(&server,sizeof(server)); server.sin_family = AF_INET; inet_pton(AF_INET,argv[1],&server.sin_addr); server.sin_port = htons(8889); if((n=connect(socketfd,(SA *)&server,sizeof(server)))<0) { printf("connect error...\n"); exit(0); } while(fgets(buff,1024,stdin)!=NULL) { write(socketfd,buff,strlen(buff)); n=read(socketfd,buff,1023); buff[n+1]+='\0'; printf("The client received message is: %s\n",buff); } close(socketfd); }服务器端代码如下:#include <stdio.h>#include <stdlib.h>#include <string.h> /*bzero library */#include <sys/socket.h> /* socket functions */#include <netinet/in.h> /* socket structs */#define SA struct sockaddrint main(int argc, char **argv){ int listenfd,connectfd,n,clilen; struct sockaddr_in server,client; char buff[1024]; if((listenfd = socket(AF_INET,SOCK_STREAM,0))<0) { printf("socket creation error...\n"); exit(0); } bzero(&server,sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(8889); if((n=bind(listenfd,(SA *)&server,sizeof(server)))<0) { printf("bind error...\n"); exit(0); } if((n=listen(listenfd,5))<0){ printf("Listen error...\n"); exit(0); } for(;;){ clilen=sizeof(client); if((connectfd=accept(listenfd,(SA *)&client,&clilen))<0) { printf("Accept error...\n"); exit(0); } while((n=read(connectfd,buff,1023))>0) { buff[n+1]+='\0'; printf("The received message is: %s\n",buff); write(connectfd,buff,1023); } close(connectfd); }}在LINUX先运行服务器端,再用客户端连接,能运行但是出现乱码,请问下怎么解决?(好像用fputs 什么什么的)

解决办法:
1.在客户端n=read(socketfd,buff,1023);代码之前加上memset(buff,0,sizeof(buff));,这是保证收到较短数据(使用TCP你不能保证每次接收的数据和发送的数据时等长的),打印也是正确的;
2.将客户端buff[n+1]+='\0';修改为buff[n]='\0';,这是因为n是下标,已经是最后一个位置了;
3.将服务器端buff[n+1]+='\0';修改为buff[n]='\0';,这是因为n是下标,已经是最后一个位置了,而且和第2)一样,那个加号也要去掉,应该是笔误吧;
4.最大的问题,将服务器端write(connectfd,buff,1023);,你怎么能够保证收到1023个字符呢?也应该将while中条件移出作为WHILE中的一条语句,而且加上前面所述的memset语句,而将这里的write(connectfd,buff,1023);修改为write(connectfd,buff,strlen(buff))。
祝共同进步!
温馨提示:内容为网友见解,仅供参考
第1个回答  2012-02-13
在服务器和客户端中,当你要使用buff接受或者发送前先进行memset或者bzero
相似回答