【发布时间】:2018-03-31 17:55:25
【问题描述】:
我刚刚开始了一项任务,我必须创建一个简单的服务器来处理 http 请求。
为了让我开始,我决定创建一个基本服务器,它等待连接,然后不断打印从 read() 接收到的任何内容。
使用此代码进行打印,我希望看到一个纯文本 http 请求,其中 \r 和 \n 分别替换为 <\r> 和 <\n>(当我在我的网络浏览器中访问 http://ip:port 时):
char buffer[buffer_size];
size_t bytes;
while ((bytes = read(s, buffer, buffer_size - 1)) > 0) {
buffer[bytes] = '\0';
int i = 0;
while(buffer[i] != '\0') {
if (buffer[i] == '\n') {
printf("%s","<\\n>\n");
} else if (buffer[i] == '\r') {
printf("%s","<\\r>");
} else {
printf("%c",buffer[i]);
}
i++;
}
}
然而,相反,我只是让我的控制台交替发送<\r> 和一些奇怪的正方形,里面写着看起来像 001B 的东西(这里是我的终端图片的链接http://gyazo.com/13288989dc0c1f4782052a1914eb7f84)。这是我的代码有问题吗? Mozilla 是否会故意发送这些垃圾邮件?
编辑:我的所有代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define buffer_size 1024
int main(int argc, char **argv) {
int port;
int client;
struct sockaddr_in6 my_add;
struct sockaddr_in6 their_add;
socklen_t their_add_size = sizeof(their_add);
if (argc != 2) {
printf("%s\n","Usage: ./server <port>");
return -1;
}
port = atoi(argv[1]);
my_add.sin6_family = AF_INET6;
my_add.sin6_addr = in6addr_any;
my_add.sin6_port = htons(port);
int s = socket(PF_INET6, SOCK_STREAM, 0);
if (s < 0) {
printf("%s","error on socket()");
return -1;
}
if (bind (s, (struct sockaddr *) &my_add, sizeof(my_add)) != 0) {
printf("%s","error on bind()");
return -1;
}
if (listen (s, 5) != 0) {
printf("%s","error on listen()");
return -1;
}
client = accept(s, (struct sockaddr *) &their_add, &their_add_size);
printf("%s","connected");
char buffer[buffer_size];
size_t bytes;
while ((bytes = read(s, buffer, buffer_size - 1)) > 0) {
buffer[bytes] = '\0';
int i = 0;
while(buffer[i] != '\0') {
if (buffer[i] == '\n') {
printf("%s","<\\n>\n");
} else if (buffer[i] == '\r') {
printf("%s","<\\r>");
} else {
printf("%c",buffer[i]);
}
i++;
}
}
if (bytes != 0) {
printf("%s","something went wrong. bytes != 0.");
return -1;
}
printf("%s", "connection closed");
close(s);
return 0;
}
【问题讨论】:
-
调试器显示缓冲区中的内容是什么?
-
@pm100 抱歉,我不确定您的意思?我基本上只是将 emacs 用作文本编辑器并在终端中编译
-
你应该学习如何在调试器下运行你的程序。在将成为 gdb 的 linux 上,您可以暂停程序检查数据等 google 'getting started with gdb'