在c中只能与Client连接一次Server

时间:2018-04-22 23:15:18

标签: c sockets server client

我正在用C语言编写并创建一个服务器,该服务器一次接收来自多个不同客户端的连接。但是,在第一个连接关闭后,服务器无法再次连接。

server.c:

#include <stdio.h>
#include <stdlib.h>

#include <sys/socket.h>
#include <sys/types.h>

#include <netinet/in.h>
#include <unistd.h>

int main() {
 while(1) {
  char server_message[256] = "You have reached the server!";

  //Create a socket
  int server_socket;
  server_socket = socket(AF_INET, SOCK_STREAM, 0);

  //Define the server address
  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 the socket to the IP and port
  bind(server_socket, (struct sockaddr *) &server_address, 
  sizeof(server_address));

  //Listen for connections
  listen(server_socket, 5);

  //Accept the connection
  int client_socket = accept(server_socket, NULL, NULL);

  //Send message
  send(client_socket, server_message, sizeof(server_message), 0);

  //Close the socket
  close(server_socket);
  }
 return 0;
}

2 个答案:

答案 0 :(得分:2)

您正在循环创建服务器套接字,接受一个连接,处理它,然后关闭服务器套接字。最后一个操作将丢弃所有挂起的连接。您的循环应该在listen()调用后立即启动,并在关闭客户端套接字后终止,并在关闭服务器套接字之前

您也忽略了socket(), bind(), listen(), accept(), send()close()上的所有错误。不要那样做。

答案 1 :(得分:0)

像这样更改代码(省略错误检查):

int main() {

  //Create a socket
  int server_socket;
  server_socket = socket(AF_INET, SOCK_STREAM, 0);

  //Define the server address
  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 the socket to the IP and port
  bind(server_socket, (struct sockaddr *) &server_address, 
  sizeof(server_address));

  //Listen for connections
  listen(server_socket, 5);

 while(1) {
  char server_message[256] = "You have reached the server!";

   //Accept the connection
   int client_socket = accept(server_socket, NULL, NULL);
   /*check some condition to exit from loop*/

   /*or send client to another thread for parallel programing*/

   //Send message
   send(client_socket, server_message, sizeof(server_message), 0);

   //Close the client socket
   close(client_socket);
  }

  close(server_socket);

 return 0;
}

在此代码服务器中,get客户端必须等待客户端完成它的工作,然后尝试接受新客户端,如果要并行,接受客户端中的客户端和数据传输,最好将客户端发送和接收放在另一个线程中。