通过套接字进行C服务器 - 客户端通信 - 如何从服务器到客户端打印消息

时间:2017-04-22 16:42:03

标签: c sockets server client communication

我的服务器有问题。他无法向客户发送基本信息。 我认为问题出在客户端,因为他无法接收已发送的消息,但我不知道如何解决这个问题:/

我的服务器:

int server(){
  int lis_soc,s,r;
  struct sockaddr_un ad;
  char buffer[MAXSIZE];

  lis_soc=socket(AF_UNIX,SOCK_STREAM,0);
  memset(&ad,0,sizeof(ad));
  ad.sun_family=AF_UNIX;
  strcpy(ad.sun_path,"./sock");

  unlink("./sock");
  bind(lis_soc,(struct sockaddr *) &ad,sizeof(ad));
  listen(lis_soc,10);
  s=accept(lis_soc,0,0);
  while(strcmp(buffer,"halt")!=0 && strcmp(buffer,"quit")!=0){
      char *pch=(char *)malloc(MAXSIZE);

    bzero(buffer,MAXSIZE);
    r=read(s,buffer,sizeof(buffer));
    strcpy(pch,buffer);
    strtok(pch," ");

    if(strcmp(buffer,"help")==0) get_help(s);  //this is the funcion for print from server
    else if(strcmp(buffer,"info")==0) get_info();
    else if(strcmp(buffer,"run")==0) run();
    else if(strcmp(pch,"ls")==0){
      if(strcmp(buffer,"ls")==0) ls(".",NULL);
      else while ((pch = strtok (NULL, " ")) != NULL) {ls(pch,NULL);}
    }
    else system(buffer);
  }
  close(s);
  printf("SERVER END OF CONNECTION\n");
  return 0;
}

我的客户:

int client(){
    int s,r;
    char buffer[MAXSIZE];
    char output[]="client: Enter data for server: ";
  struct sockaddr_un ad;

  s=socket(AF_UNIX,SOCK_STREAM,0);
  memset(&ad,0,sizeof(ad));
  ad.sun_family=AF_UNIX;
  strcpy(ad.sun_path,"./sock");

  connect(s,(struct sockaddr *) &ad,sizeof(ad));
  while(strcmp(buffer,"halt")!=0 && strcmp(buffer,"quit")!=0){
    bzero(buffer,MAXSIZE);
    write(1,output,strlen(output));
    r=read(0,buffer,sizeof(buffer));
    buffer[r-1]='\0';
    write(s,buffer,strlen(buffer));
  }
  close(s);
  printf("CLIENT END OF CONNECTION\n");
  return 0;
}

从服务器调用函数get_help():

void get_help(int lis_soc){
  char buffer[]="Ahoj client";
  write(lis_soc,&buffer,strlen(buffer));
}

在我的功能调用后得到帮助没有打印出来。为什么呢?

1 个答案:

答案 0 :(得分:0)

您的客户端代码不会读取它从服务器获取的消息。

我编译并执行了你的代码,以仔细检查这是否是问题。

只需在客户端的while循环结束时添加read(s, ...);调用:

while(strcmp(buffer,"halt")!=0 && strcmp(buffer,"quit")!=0){
    bzero(buffer,MAXSIZE);
    write(1,output,strlen(output));
    r=read(0,buffer,sizeof(buffer));
    buffer[r-1]='\0';
    write(s,buffer,strlen(buffer));
    read(s, buffer, sizeof(buffer));
    printf("Answer from server: %s\n",buffer);
}