我正在尝试在 C++ 中创建一个简单的客户端服务器程序。服务器和客户端执行直到终止,但数据不会从服务器传输到客户端。我的服务器代码是:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
int main(void) {
int sid=socket(AF_INET,SOCK_STREAM,0);
int clilen;
int clisocket;
char buffer[256];
int portnumber=atoi("8888");
struct sockaddr_in serverinfo,cliinfo;
memset(&serverinfo, '0', sizeof(serverinfo));
memset(&cliinfo, '0', sizeof(cliinfo));
serverinfo.sin_family=AF_INET;
serverinfo.sin_port=htons(portnumber);
serverinfo.sin_addr.s_addr=INADDR_ANY;
bind(sid,(struct sockaddr *)&serverinfo,sizeof(serverinfo));
listen(sid,1000);
clilen=sizeof(clilen);
clisocket=accept(sid,(struct sockaddr*)&cliinfo,(socklen_t*)clilen);
bzero(buffer,256);
printf("before server \n");
write(clisocket,"hello",5);
printf("after server \n");
close(clisocket);
close(sid);
return 0;
}
我的客户代码是:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
int main(void) {
char buffer[256];
bzero(buffer,256);
int cid=socket(AF_INET,SOCK_STREAM,0);
int port=atoi("8888");
struct sockaddr_in serverinfo;
memset(&serverinfo, '0', sizeof(serverinfo));
struct hostent* host;
memset(&host, '0', sizeof(host));
host=gethostbyname("localhost");
serverinfo.sin_family=host->h_addrtype;
memcpy((char *) &serverinfo.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
serverinfo.sin_port=htons(port);
int statusconnect=connect(cid,(sockaddr*)&serverinfo,sizeof(serverinfo));
printf("before read client \n");
read(cid,buffer,255);
printf("after client read");
printf(buffer); //not print this!!!
printf(buffer);
close(cid);
return 0;
}
我将不胜感激任何帮助。