我正在尝试在Linux中创建客户端服务器应用程序。服务器将对象发送到客户端,但客户端写入细分故障。这是代码。蛇是二维阵列的类。
客户端发送消息" p",服务器正在创建对象女巫将被发送到客户端。
服务器端:
int main(int argc, char *argv[])
{
int sockfd, newsockfd;
socklen_t cli_len;
struct sockaddr_in serv_addr, cli_addr;
int n;
char buffer[256];
if (argc < 2)
{
fprintf(stderr,"usage %s portn", argv[0]);
return 1;
}
bzero((char*)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(atoi(argv[1]));
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("Error creating socket");
return 1;
}
if (bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
perror("Error binding socket address");
return 2;
}
while(sockfd){
listen(sockfd, 5);
cli_len = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &cli_len);
if (newsockfd < 0)
{
perror("ERROR on accept");
return 3;
}
bzero(buffer,256);
n = read(newsockfd, buffer, 255);
if (n < 0)
{
perror("Error reading from socket");
return 4;
}
// if client send 'p'
if(*buffer == 'p' ){
Snake *snake = new Snake();
send(newsockfd,reinterpret_cast<const char*>(&snake), sizeof(snake),0);
}
}
//printf("Here is the message: %sn", buffer);
const char* msg = "I got your message";
n = write(newsockfd, msg, strlen(msg)+1);
if (n < 0)
{
perror("Error writing to socket");
return 5;
}
close(newsockfd);
close(sockfd);
}
客户端:
int main(int argc, char *argv[])
{
int sockfd = 0,newsockfd, n;
struct sockaddr_in serv_addr;
struct hostent* server;
socklen_t cli_len, serv_len;
char buffer[999999];
struct sockaddr_in cli_addr;
if (argc < 3)
{
fprintf(stderr,"usage %s hostname portn", argv[0]);
return 1;
}
server = gethostbyname(argv[1]);
if (server == NULL)
{
fprintf(stderr, "Error, no such hostn");
return 2;
}
bzero((char*)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy(
(char*)server->h_addr,
(char*)&serv_addr.sin_addr.s_addr,
server->h_length
);
serv_addr.sin_port = htons(atoi(argv[2]));
//while(sockfd >= 0){
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("Error creating socket");
return 3;
}
if(connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
perror("Error connecting to socket");
return 4;
}
printf("Please enter a message: ");
bzero(buffer,256);
fgets(buffer, 255, stdin);
n = write(sockfd, buffer, strlen(buffer));
if (n < 0)
{
perror("Error writing to socket");
return 5;
}
Snake *snake ;
recv(sockfd,reinterpret_cast<char*>(&snake), sizeof(snake),0);
if (n < 0)
{
perror("Error reading from socket");
return 6;
}
printf("%sn",buffer);
close(sockfd);
close(newsockfd);
return 0;
}
谢谢您的回答。
在客户端
Snake *snake ;
recv(sockfd,reinterpret_cast<char*>(&snake), sizeof(snake),0);
试图读入蛇,但您还没有创建任何内容。因此,非初始化的指针给您分段故障。
另外,sizeof(snake)
是指针的大小(例如4个字节),而不是指向对象的大小。这既发生在服务器和客户端中。