【问题标题】:recv() - Working with HTTP headersrecv() - 使用 HTTP 标头
【发布时间】:2011-03-08 18:03:29
【问题描述】:

下面是代码,我取自 MSDN 的 Winsock 服务器编程教程示例。代码似乎工作正常。当我在浏览器中键入 http://localhost:27015 时,代码会做出适当的响应。但是,我无法使用浏览器作为请求发送并作为字符数组存储在 recvbuf 中的字符串。例如,我无法 printf 缓冲区或使用 fwrite 。程序立即终止。请帮忙。

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>


// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(void)
{
WSADATA wsaData;
SOCKET ListenSocket = INVALID_SOCKET,
       ClientSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
                hints;
char recvbuf[DEFAULT_BUFLEN];
char *sendbuf = "HTTP/1.1 200 OK \r\n Date: Fri, 31 Dec 1999 23:59:59 GMT \r\n Content-     Type: text/html\r\n";
int iResult, iSendResult;
int recvbuflen = DEFAULT_BUFLEN;

// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
    printf("WSAStartup failed with error: %d\n", iResult);
    return 1;
}
else
    printf("\nInitialising winsock...done");

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;

// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
    printf("getaddrinfo failed with error: %d\n", iResult);
    WSACleanup();
    return 1;
}
else
    printf("\nResolving server address...done");
//localhost:27015/
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
    printf("socket failed with error: %ld\n", WSAGetLastError());
    freeaddrinfo(result);
    WSACleanup();
    return 1;
}
else
    printf("\nCreating connection socket...done");

// Setup the TCP listening socket
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
    printf("bind failed with error: %d\n", WSAGetLastError());
    freeaddrinfo(result);
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}
else
    printf("\nCreating listening socket...done");
    printf("\nWaiting for connection... ");

freeaddrinfo(result);

iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
    printf("listen failed with error: %d\n", WSAGetLastError());
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}

// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
    printf("accept failed with error: %d\n", WSAGetLastError());
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}

// No longer need server socket
closesocket(ListenSocket);

// Receive until the peer shuts down the connection
do
{
    iResult = recv(ClientSocket, recvbuf, recvbuflen,0);
    if (iResult > 0) {
        printf("Bytes received: %d\n", iResult);

        // Echo the buffer back to the sender
        iSendResult = send(ClientSocket,sendbuf,(int)strlen(sendbuf), 0 );
        if (iSendResult == SOCKET_ERROR) {
            printf("send failed with error: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }
        printf("Bytes sent: %d\n", iSendResult);
    }
    else if (iResult == 0)
        printf("Connection closing...\n");
    else {
        printf("recv failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }
}while(iResult>0);

// shutdown the connection since we're done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
    printf("shutdown failed with error: %d\n", WSAGetLastError());
    closesocket(ClientSocket);
    WSACleanup();
    return 1;
}
// cleanup
closesocket(ClientSocket);
WSACleanup();
//Appended later  
printf("\n");
int i =0;
while(i<120)
{
    printf("%c",recvbuf[i]);
    ++i;
}
return 0;

}

谢谢!

【问题讨论】:

  • 我没有看到你试图用 recvbuf 做任何事情,究竟是什么代码失败了?
  • 请参考OP中的编辑版本。 (上面的六行返回 0。)程序在浏览器连接到服务器的那一刻终止。没有提到任何错误。

标签: c http sockets winsock


【解决方案1】:
iResult = recv(ClientSocket, recvbuf, recvbuflen,0);

在上面,通过recv() 接收到的数据不是以零结尾的。 iResult是数据的长度,输出为文本:

printf("%.*s", iResult, recvbuf);

【讨论】:

  • 嗨,这个也没有帮助。
【解决方案2】:

添加以下功能有所帮助。马克西姆说的时候已经给出了提示

通过 recv() 接收到的数据不是 零终止。

void handleBuffer()
{
    recvbuf[DEFAULT_BUFLEN-1]='\0';
    printf("*********************\n");
    printf("%s",recvbuf);
}

我还将我的 DEFAULT_BUFLEN 增加到 4096。随时调用该函数来打印输出。

【讨论】:

  • 带星号的 printf 仅用于隔离目的。
猜你喜欢
  • 2014-09-20
  • 2011-12-21
  • 2023-03-18
  • 1970-01-01
  • 2018-12-17
  • 2017-10-22
  • 2013-05-22
  • 2012-01-09
  • 1970-01-01
相关资源
最近更新 更多