服务器没有正确接收消息?

时间:2014-01-26 14:08:44

标签: c linux networking

我是C网络新手,我一直试图让服务器从客户端检索消息,但写消息仍然失败。当我这样做时,我基本上试图修改一个从服务器接收消息的程序来发送它。这是服务器代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define PORTNUM 1887

int server() {
  char msg[101];

  struct sockaddr_in dest;
  struct sockaddr_in serv;
  int mysocket;
  socklen_t socksize = sizeof(struct sockaddr_in);

  memset(&serv, 0, sizeof(serv));

  serv.sin_family = AF_INET;
  serv.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  serv.sin_port = htons(PORTNUM);

  mysocket = socket(AF_INET, SOCK_STREAM, 0); 
  bind(mysocket, (struct sockaddr *)&serv, sizeof(struct sockaddr));

  listen(mysocket, 2); 
  int consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
  int len;

  while (consocket) {
    printf("Incoming connection from %s - recieving welcome\n", inet_ntoa(dest.sin_addr));
    len = recv(mysocket, msg, 100, 0); 
    msg[len] = '\0';
    if (len > 0) printf("%s %d\n", msg, len);
    consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
  }
  close(consocket);
  close(mysocket);
  return EXIT_SUCCESS;
}

int main() {
  return server();
}

这是客户。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>


#define MAXREC 100
#define PORTNUM 1887

int getMessage() {
  char buffer[] = "Hello Fish!\n";
  int len, mysocket;
  struct sockaddr_in dest;

  mysocket = socket(AF_INET, SOCK_STREAM, 0);

  memset(&dest, 0, sizeof(dest));
  dest.sin_family = AF_INET;
  dest.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  dest.sin_port = htons(PORTNUM);

  connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr));
  printf("%s\n", buffer);
  write(mysocket,"45", strlen("45"));


  close(mysocket);
  return EXIT_SUCCESS;
}

int main() {
  return getMessage();
}

最初我尝试发送缓冲区消息,然后我切换到尝试使用常量来查看是否有帮助。

1 个答案:

答案 0 :(得分:3)

len = recv(mysocket, msg, 100, 0); 
服务器上的

应该是

len = recv(consocket, msg, 100, 0); 

accept返回新连接的句柄,因此您需要读取客户端消息的句柄。