我在 Linux 的服务器端套接字(使用 Telnet 客户端)上工作。客户端需要以某种格式输入一行:命令(GET/PUT/DEL)键和相关值(中间用空格分隔)。这个键值对随后相应地传递给函数(GET/PUT/DEL),该函数将数据保存在共享内存(keyValueStore)中。
在尝试将输入分成 3 个部分之前,我发现了两个问题
1/ bytes_index 不是我所期望的(黄色)
2/ 服务器不显示以下几行(在 if (bytes_index > 0) 内)
例如获取 key1 嗨
printf("%s\n", input[0]); //G
printf("%s\n", input[1]); //e
printf("%s\n", input[2]); //t
-我可以知道原因吗?如果可能的话,有什么解决方法的提示吗?谢谢!
main.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUFSIZE 1024 // Buffer Size
#define TRUE 1
#define PORT 5678
int main() {
int rfd; // Create-Descriptor
int cfd; // Connection-Descriptor (accept)
struct sockaddr_in client;
socklen_t client_len;
char input[BUFSIZE];
int bytes_read;
// 1. socket()
rfd = socket(AF_INET, SOCK_STREAM, 0);
if (rfd < 0 ){
fprintf(stderr, "Error\n");
exit(-1);
}
//Initialize the server address by the port and IP
struct sockaddr_in server;
memset(&server, '\0', sizeof(server));
server.sin_family = AF_INET; // Internet address family: v4 address
server.sin_addr.s_addr = INADDR_ANY; // Server IP address
server.sin_port = htons(PORT); // Server port
// 2. bind()
int brt = bind(rfd, (struct sockaddr *) &server, sizeof(server));
if (brt < 0 ){
fprintf(stderr, "Error\n");
exit(-1);
}
// 3. listen() = listen for connections
int lrt = listen(rfd, 5);
if (lrt < 0 ){
fprintf(stderr, "Error\n");
exit(-1);
}
while (1) {
// 4. accept() = accept a new connection on socket from client
cfd = accept(rfd, (struct sockaddr *) &client, &client_len);
if (cfd < 0) {
fprintf(stderr, "accept failed with error %d\n");
exit(-1);
}
printf("Client connected\n");
while (1) {
int bytes_index = -1;
while (1) {
bytes_read = recv(cfd, &input[++bytes_index], 1, 0);
if (bytes_read <= 0) // Check error or no data read
break;
if (input[bytes_index] == '\n') {
// Received a complete line, including CRLF
// Remove ending CR
bytes_index--;
if ((bytes_index >= 0) && (input[bytes_index] == '\r'))
input[bytes_index] = 0;
break;
}
}
if (bytes_index > 0) { // Check for empty line
printf("%s\n", input);
printf("bytes_index: %d\n", bytes_index);
printf("%s\n", input[0]);
printf("%s\n", input[1]);
printf("%s\n", input[2]);
// Check for client command
if (strcmp(input, "QUIT") == 0)
break;
}
}
close(cfd);
printf("Client disconnected\n");
}
close(rfd);
}