我在c中创建了一个模拟航空公司的服务器/客户端tcp连接。我在从服务器向客户端发送航班列表时遇到问题,我当时只能发送一串字符,而且我实施的代码无效,给我一个分段错误,有人可以给我一些内幕吗?
这是服务器,send_all()函数将使用套接字ID和hashmap逐行发送带有write()函数的航班列表。
int send_all(int socket, map_t flight_map)
{
struct hashmap_element {
char* key;
int in_use;
any_t data;
};
struct hashmap_map {
int table_size;
int size;
struct hashmap_element *data;
};
struct hashmap_map * map = (struct hashmap_map *) flight_map;
//int index = map->tableSize;
char line[12];
int i = 0;
for (i = 0; i < map->table_size; i++)
{
strcpy(line, return_flight(map->data[i].key, map->data[i].data));
if (write(socket, line, strlen(line) + 1) < 0) {
error("error: writing to connection");
return 0;
}
}
return 1;
}
char * return_flight(char * flight, void * seats)
{
char tmp[20];
strcpy(tmp, flight);
strcat(tmp, (char *)seats);
return tmp;
}
以下是客户端: readSocket,负责读取通过套接字连接传递的每一个字符串...
// send input to server
if (write(client_fd, command, strlen(command) + 1) < 0)
error("error: writing to socket");
printf("client: sending %s to server\n", command);
// recieve response from server
if (readSocket(client_fd, buffer) < 0)
error("error: reading from socket");
printf("client: read %s from server\n", buffer);
printf("client: closing client\n");
close(client_fd);
}
return 0;
}
static int readSocket(int socket, char *buffer)
{
ssize_t bytes_read = 0;
bytes_read = recv(socket, buffer, BUFSIZE - 1, 0);
while (bytes_read > 0)
{
buffer[bytes_read] = 0; // Null-terminate the buffer
printf("Buffer: %s\n", buffer);
bytes_read = recv(socket, buffer, BUFSIZE - 1, 0);
}
if (bytes_read == -1)
{
fprintf("Socket recv failed: %s\n", strerror(errno));
return -1;
}
return 0;
}