首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c++ winsock多线程http服务器

c++ winsock多线程http服务器
EN

Stack Overflow用户
提问于 2014-09-19 12:33:13
回答 1查看 1.5K关注 0票数 0

我对C++非常陌生,遇到了一个问题,当我连接到服务器(使用浏览器)时,它会发送一个很好的响应,并且它在浏览器上显示得很好,然而,看看它发送给网页两次的控制台,页面视图计数器就会确认这一点,通过测试我不确定它运行的顺序。

循环侦听新连接:

代码语言:javascript
复制
    while (true){

    //create temp scoket for cconnetcion
    SOCKET ClientSocket;
    ClientSocket = INVALID_SOCKET;
    // Accept the socket from the client when it tries to connect
    ClientSocket = accept(ListenSocket, NULL, NULL);

    printf("NEWCON" );
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed: %d\n", WSAGetLastError());
        std::string blah;
        std::cin >> blah;
        closesocket(ListenSocket);
        WSACleanup();
        return 104;
    }

    views += 1;

    AfxBeginThread(RequestProsorses, (LPVOID)ClientSocket);

}

RequestProsorses函数:

代码语言:javascript
复制
UINT  RequestProsorses(LPVOID pParam){
printf("\n NEWREC");
SOCKET ClientSocket = (SOCKET)pParam;


 #define DEFAULT_BUFLEN 512

char recvbuf[DEFAULT_BUFLEN];
int conResult, iSendResult;
int recvbuflen = DEFAULT_BUFLEN;
std::string returnVal = "HTTP/1.x 200 OK \n Transfer-Encoding: chunked \n\n <html><body><b>Total Page Views:</b>";

conResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (conResult > 0) {
    printf("Bytes received: %d\n", conResult);

    //create response to user
    returnVal +=   std::to_string(views) + "</body></html>";
    //printf(returnVal.c_str());
    // Send Responce to user

    iSendResult = send(ClientSocket, returnVal.c_str(), returnVal.length(), 0);
    if (iSendResult == SOCKET_ERROR) {
        //printf("send failed: %d\n", WSAGetLastError());
        std::string blah;
        std::cin >> blah;
        closesocket(ClientSocket);
        WSACleanup();
    }
    printf("Bytes sent: %d\n", iSendResult);
}
else if (conResult == 0){
    printf("Connection closing...\n");
}
else {
    printf("recv failed: %d\n", WSAGetLastError());
    std::string blah;
    std::cin >> blah;
    closesocket(ClientSocket);
    WSACleanup();
}

// shutdown the send half of the connection since no more data will be sent
conResult = shutdown(ClientSocket, SD_SEND);
if (conResult == SOCKET_ERROR) {
    printf("shutdown failed: %d\n", WSAGetLastError());
    closesocket(ClientSocket);
    WSACleanup();
}

closesocket(ClientSocket);

return 0;
}

控制台输出(仅为一个视图):

新新世 NEWREC 收到NEWRECBytes : 373 发送字节: 99 字节重编码: 287 发送字节:99

希望这是足够的信息给你,如果不是,我很高兴张贴更多当然。

语句以检查标头的敌对端。

代码语言:javascript
复制
    for (int i = 0; i <= recvbuflen; i++){
    if (recvbuf[i] == '\n' && (int)recvbuf[i + 1] == -52){
        finished = true;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-19 17:16:33

我找到了答案:),感谢@JoachimPileborg和@MartinJames的帮助!简单地说,浏览器发送的是第二个请求,由于程序不检查正在查看的页面(它只是发送相同的页面,无论目前是什么),在我看来,它只为一个页面请求做了两次相同的事情。浏览器试图对/favicon.ico进行评估,就像它所设想的那样。

我已经对代码进行了更改,虽然它还没有完成,但是如果有人对我所做的更改感兴趣,请看下面的代码(在那里,我修复了其他错误,而没有意识到)。

代码语言:javascript
复制
// HTMLtest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <iostream>
#include <thread>
#include <afxwin.h>
#include <winsock2.h>
#include <ws2tcpip.h>

#pragma comment(lib, "Ws2_32.lib")


int views = 0;

UINT  RequestProsorses(LPVOID pParam){
    printf("\n NEWREC");
    SOCKET ClientSocket = (SOCKET)pParam;
#define DEFAULT_BUFLEN 512

char recvbuf[DEFAULT_BUFLEN];
int conResult, iSendResult;
int recvbuflen = DEFAULT_BUFLEN;
std::string returnVal = "HTTP/1.x 200 OK \n Transfer-Encoding: chunked \n\n <html><body><b>Total Page Views:</b>";
bool finished = false;
do {
    std::cout << "b";
conResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
for (int i = 0; i <= recvbuflen; i++){
    if (recvbuf[i] == '\n' && (int)recvbuf[i + 1] == -52){
        finished = true;
    }
}

if (conResult > 0) {

}
else if (conResult == 0){
    printf("Connection closing...\n");
}
else {
    printf("recv failed: %d\n", WSAGetLastError());
    std::string blah;
    std::cin >> blah;
    closesocket(ClientSocket);
}



} while (conResult > 0 && finished == false);

printf("Bytes received: %d\n", conResult);
std::cout << "RECIVED: " << recvbuf;
//create response to user
returnVal += std::to_string(views) + "</body></html>";
//printf(returnVal.c_str());
// Send Responce to user

iSendResult = send(ClientSocket, returnVal.c_str(), returnVal.length(), 0);
if (iSendResult == SOCKET_ERROR) {
    printf("send failed: %d\n", WSAGetLastError());
    std::string blah;
    std::cin >> blah;
    closesocket(ClientSocket);
}
printf("Bytes sent: %d\n", iSendResult);



closesocket(ClientSocket);

return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{

WSADATA wsaData;

// Initialize Winsock
int IPresult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (IPresult != 0) {
    printf("WSAStartup failed: %d\n", IPresult);
    return 1;
}

struct addrinfo *result = NULL, *ptr = NULL, params;
ZeroMemory(&params, sizeof(params));
params.ai_family = AF_INET;
params.ai_socktype = SOCK_STREAM;
params.ai_protocol = IPPROTO_TCP;
params.ai_flags = AI_PASSIVE;

//resolve the IP address and port to used by the server
IPresult = getaddrinfo(NULL, "80", &params, &result);
if (IPresult != 0) {
    printf("getaddrinfo failed: %d\n", IPresult);
    std::string blah;
    std::cin >> blah;
    WSACleanup();
    return 100;
}


SOCKET ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);

if (ListenSocket == INVALID_SOCKET) {
    printf("Error at socket(): %ld\n", WSAGetLastError());
    std::string blah;
    std::cin >> blah;
    freeaddrinfo(result);
    WSACleanup();
    return 101;
}

// Setup the socket for HTTP
IPresult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (IPresult == SOCKET_ERROR) {
    printf("bind failed with error: %d\n", WSAGetLastError());
    std::string blah;
    std::cin >> blah;
    freeaddrinfo(result);
    closesocket(ListenSocket);
    WSACleanup();
    return 102;
}

//Free the memory allocated by "getadderinfo" as its no longe needed
freeaddrinfo(result);

if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) {
    printf("Listen failed with error: %ld\n", WSAGetLastError());
    std::string blah;
    std::cin >> blah;
    closesocket(ListenSocket);
    WSACleanup();
    return 103;
}


while (true){

    //create temp scoket for cconnetcion
    SOCKET ClientSocket;
    ClientSocket = INVALID_SOCKET;
    // Accept the socket from the client when it tries to connect
    ClientSocket = accept(ListenSocket, NULL, NULL);

    printf("NEWCON" );
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed: %d\n", WSAGetLastError());
        std::string blah;
        std::cin >> blah;
        closesocket(ListenSocket);
        WSACleanup();
        return 104;
    }

    views += 1;

    AfxBeginThread(RequestProsorses, (LPVOID)ClientSocket);

}

// cleanup
//closesocket(ClientSocket);
WSACleanup();
return 0;
}

对不起,它是如此混乱:/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25934052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档