服务器未从客户端接收信息?

时间:2018-11-22 22:08:14

标签: c sockets

我正在尝试将命令从客户端传递到服务器。但是,客户端正在完美地扫描用户输入,但是服务器只是关闭而未打印除新行以外的任何内容。

服务器:顺便说一句,读取功能返回的值小于零,因此这是问题所在,但无法解决。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>


int main(){
  char server_message[1024] = "You have reached the server";
  char recieved[200];
  int array[20];
  for(int i = 0; i < 20; i++){
    array[i] = rand();
  }

  int server_socket;
  server_socket = socket(AF_INET, SOCK_STREAM, 0);


  struct sockaddr_in server_address;
  server_address.sin_family = AF_INET;
  server_address.sin_port = htons(9002);
  server_address.sin_addr.s_addr = INADDR_ANY;


  bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address));

  listen(server_socket, 2);
  int client_socket;
  client_socket = accept(server_socket, NULL, NULL);
  recv(server_socket, &recieved, sizeof(recieved, 0), NULL);
  printf("%s", recieved);
  printf("\n");
  printf("%s", recieved);
  close(server_socket);
  return 0;
}

客户端:它可以完美地建立网络,并将命令发送到服务器进行打印。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(){
  int network_socket;
  char command[10];
  network_socket = socket(AF_INET, SOCK_STREAM, 0);


  struct sockaddr_in server_address;
  server_address.sin_family = AF_INET;
  server_address.sin_port = htons(9002);
  server_address.sin_addr.s_addr = INADDR_ANY;
  int connection_status = connect(network_socket, (struct sockaddr *) &server_address, sizeof(server_address));

  if (connection_status < 0){
    perror("Connection Failed: ");
  }

  char server_response[256];
  printf("Please enter your command:\n");
  scanf("%s", command);
  int client_socket;
  client_socket = accept(network_socket, NULL, NULL);
  send(client_socket, command, sizeof(command), 0);
  //recv(network_socket, &server_response, sizeof(server_response, 0), NULL);

  printf("The Server Sent the data : %s\n",command);

  ///close(sock);
  return 0;


}

0 个答案:

没有答案