我有简单的网络服务器:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>
#include <string.h>
#include <boost/regex.hpp>
#include <boost/thread.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string.hpp>
#include "print_r.h"
#include "Pop.h"
#include "Headers.h"
//#include<thread>
char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Connection: keep-alive\r\n"
"Server: michal\r\n"
"Set-Cookie: nazwa=test\r\n"
"Date: Mon, 24 Feb 2014 11:39:26 GMT\r\n"
"Vary: Accept-Encoding\r\n\r\n"
"<html><body><h1>It works!</h1>"
"<p>This is the default web page for this server.</p>"
"<p>The web server software is running but no content has been added, yet.</p>"
"<form method='post' action='/' enctype='multipart/form-data' ><input type='file' name='pliczek1'/><input type='submit' name='sub' value='sender' /><input type='checkbox' name='add[]' value='100001_used' ><input type='hidden' name='hidd' value='testowy hiddenik' /><input type='checkbox' name='add[]' value='100002_used' ><textarea name='txtform'>tekstowe poleąś</textarea></form>"
"</body></html>\r\n\r\n";
void app(int client_fd)
{
int buffSize = 512;
char buff[buffSize];
std::string headers = "";
int i = 0;
int npos = 0;
int a = 0;
while (i = recv(client_fd, buff, buffSize, 0))
{
std::cout << i << "\n";
bzero(buff, buffSize);
a++;
if (i < buffSize) break;
}
write(client_fd, response, sizeof(response) - 1); /*-1:'\0'*/
close(client_fd);
}
int main()
{
int one = 1, client_fd;
struct sockaddr_in svr_addr, cli_addr;
socklen_t sin_len = sizeof(cli_addr);
std::cout << sizeof(cli_addr);
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
err(1, "can't open socket");
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));
int port = 8080;
svr_addr.sin_family = AF_INET;
svr_addr.sin_addr.s_addr = INADDR_ANY;
svr_addr.sin_port = htons(port);
if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {
close(sock);
err(1, "Can't bind");
}
listen(sock, 5);
while (1) {
client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
std::cout << "\n\n+++++++++++++ NEW CLIENT +++++++++++++++\n\n\n";
if (client_fd == -1) {
std::cout << ("Can't accept\n");
break;
}
app(client_fd);
}
}
我正在尝试通过网络浏览器发送附件。对于小于21kB的文件,它工作正常,但我不能发送超过21845字节。为什么呢?
答案 0 :(得分:2)
您违反了一条非常重要的规则:始终检查API调用的返回值。
特别是,您不检查write
的返回值,只是假设成功。实际上,它通常只发送部分消息,因此您需要循环和错误检查。
答案 1 :(得分:0)
尝试在recv调用之间稍微延迟读取。您无法保证一次性接收所有数据。你必须等待所有数据。