?? winsockhttpclient.cpp
字號:
//****************************************************************************//
//* //
//* Copyright (C) 2003, James Antognini, antognini@mindspring.com. //
//* //
//****************************************************************************//
/**************************************************************************************************/
/* */
/* Adapted from */
/* ms-help://MS.MSDNQTR.2002JUL.1033/wcewinsk/htm/_wcecomm_TCP_Stream_Socket_Client.htm. */
/* */
/**************************************************************************************************/
#define JAProgNm "WinsockHTTPClient"
#define JAProgVersion "1.47"
#define charDfltServerAddr2 "129.42.17.99"
#define charDfltPort2 "80"
#include <winsock2.h>
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <process.h>
#include <commctrl.h>
#include <winioctl.h>
#include "TDIClient.h"
int main(
IN int nbrArgs,
IN char * pArgv[]
)
{
#define rcOK 0
#define rcError 8
#define CmdUnknown 0
#define CmdStart 1
#define CmdStop 2
#define CmdTest 3
#define CmdTest2 4
static struct
{
DWORD CmdCode;
char * pInStr;
}
InStrArr[] =
{ // Except that CmdUnknown has to be first, the following can be in any order.
{CmdUnknown, ""},
{CmdTest, "RmtServer"},
{CmdTest2, "."},
};
char static dfltIPAddr[] = // Default IP address.
charDfltServerAddr2,
dfltPort[] = charDfltPort2, // Default port.
dfltURIResource[] = "/us/", // Default URI resource.
endRecord1[] = " HTTP/1.0\r\n",
DateCompiledBase[] = __DATE__,
TimeCompiledBase[] = " "__TIME__,
JAProgInfo[] = JAProgNm " v" JAProgVersion " (compiled ";
char DateCompiled[12] = // Build date in preferred (dd mmm yyyy) format.
{DateCompiledBase[4], DateCompiledBase[5], DateCompiledBase[6],
DateCompiledBase[0], DateCompiledBase[1], DateCompiledBase[2], DateCompiledBase[3],
DateCompiledBase[7], DateCompiledBase[8], DateCompiledBase[9], DateCompiledBase[10],
0x0
},
szClientA[TDIClientRecvBfrLen];
char static * pServerBoundMessage[] = {
"GET ",
"Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"Connection: keep-alive\r\n\r\n"
};
char * pIPAddr,
* pPort,
* pURIResource;
int rcRecv, // Return value of recv function
port, // Port to use.
i,
rc = rcOK,
lnInStrArr = // Get number of instances.
sizeof InStrArr / sizeof InStrArr[0],
TotalRecvd = 0,
CmdNbr = CmdUnknown;
BOOL bFirst = TRUE;
ULONG ulTotalSend; // Total number of bytes that will be sent.
SOCKET ServerSock = INVALID_SOCKET; // Socket bound to the server
SOCKADDR_IN destination_sin; // Server socket address
PHOSTENT phostent = NULL; // Points to the HOSTENT structure of the server
WSADATA WSAData; // Contains details of the Winsocket implementation
printf("%s%s%s)\n", JAProgInfo, DateCompiled, TimeCompiledBase);
if (nbrArgs>=2)
{
for (i = 1; i < lnInStrArr; i ++) // Go through expected parameters.
if (0==_stricmp(pArgv[1], InStrArr[i].pInStr)) // Does the second parm match?
break; // If yes, break.
}
else
i = lnInStrArr; // Ensure next conditional yields supported parameter information.
if (i<lnInStrArr) // Found a supported command?
{
CmdNbr = InStrArr[i].CmdCode;
if (CmdTest2==CmdNbr) // Dot given?
CmdNbr = CmdTest; // Use full command.
}
else
{
printf("\nUnsupported command\n\n");
printf("Usage: " JAProgNm " <operand>\n\n");
printf(" where <operand> is one of these:\n\n");
for (i = 1; i < lnInStrArr; i ++)
printf(" %s\n", InStrArr[i].pInStr);
printf("\n Eg,\n\n <RmtServer | . <IP address | IP name | .> <port | . <URI resource>>>\n");
printf("\n (Capitalization is ignored.)\n");
printf("\n (Defaults: IP addr = %s, port = %s.)\n", dfltIPAddr, dfltPort);
rc = 1;
goto ExitPoint;
}
if (nbrArgs>=3)
{
pIPAddr = pArgv[2]; // Get IP address.
if (0==strcmp(pIPAddr, ".")) // Dot given?
pIPAddr = dfltIPAddr; // Point to default IP address.
}
else
pIPAddr = dfltIPAddr; // Get IP address.
if (nbrArgs>=4)
{
pPort = pArgv[3]; // Get port.
if (0==strcmp(pPort, ".")) // Dot given?
pPort = dfltPort; // Point to default port.
}
else
pPort = dfltPort; // Get port.
port = atoi(pPort); // Convert ascii to integer.
if (nbrArgs>=5)
{
pURIResource = pArgv[4]; // Get URI resource.
if (0==strcmp(pURIResource, ".")) // Dot given?
pURIResource = dfltURIResource; // Point to default URI resource
}
else
pURIResource = dfltURIResource; // Point to default URI resource
printf(" Using IP address = %s, port = %d, URI resource = %s\n", pIPAddr, port, pURIResource);
// Initialize Winsocket.
if (WSAStartup(MAKEWORD(2,0), &WSAData) != 0) // Accept up to Winsock 2.0.
{
printf(JAProgNm ": WSAStartup failed. Error = %d\n", WSAGetLastError());
return 1;
}
// Create a TCP/IP socket that is bound to the server.
if ((ServerSock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf(JAProgNm ": Allocating socket failed. Error = %d\n", WSAGetLastError());
return 1;
}
// Fill out the server socket's address information.
destination_sin.sin_family = AF_INET;
// Retrieve the host information corresponding to the host name.
if ((phostent = gethostbyname(pIPAddr)) == NULL)
{
printf(JAProgNm ": Unable to get the host name. Error = %d\n", WSAGetLastError ());
closesocket (ServerSock);
return 1;
}
// Assign the socket IP address.
memcpy((char FAR *)&(destination_sin.sin_addr),
phostent->h_addr,
phostent->h_length);
// Convert to network ordering.
destination_sin.sin_port = htons(port);
// Establish a connection to the server socket.
if (connect (ServerSock,
(PSOCKADDR) &destination_sin,
sizeof (destination_sin)) == SOCKET_ERROR)
{
ULONG error = WSAGetLastError();
printf(JAProgNm ": Connecting to the server failed. Error = %d%s\n", error, WSAECONNREFUSED==error ? " (connection refused)" : "");
closesocket (ServerSock);
return 1;
}
// Behavior: 1) send loop.
// 2) receive loop.
// Send strings to the server.
for ( // Add size of strings (including terminator), except for first.
i = 1,
ulTotalSend = 0;
i < arraysize(pServerBoundMessage);
i ++
)
ulTotalSend += strlen(pServerBoundMessage[i])+1;
// Send strings to the server.
for ( // Send loop.
i = 0;
i < 1;
// i < arraysize(pServerBoundMessage);
i ++
)
{
char * pBuffer;
ULONG sendLn = strlen(pServerBoundMessage[i])+1; // Get size of current string, including terminator.
if (0==i) // First send?
{
sendLn += strlen(pURIResource) + // Add size of URI resource and
strlen(endRecord1) + // end of first record.
strlen(pServerBoundMessage[1])+1;
pBuffer = (char *)malloc(sendLn); // Get a buffer.
if (NULL==pBuffer) // No good?
{
printf(JAProgNm ": Couldn't allocate buffer, quitting\n");
goto DoShutdown;
}
ulTotalSend += sendLn; // Add size of first string.
strcpy(pBuffer, pServerBoundMessage[0]); // Copy first part of first record.
strcat(pBuffer, pURIResource); // Append URI resource.
strcat(pBuffer, endRecord1); // Append end of first record.
strcat(pBuffer, pServerBoundMessage[1]); // Append remaining records
}
else
pBuffer = pServerBoundMessage[i]; // Point to fixed string.
printf(JAProgNm ": Sending %d bytes\n >%s<\n", sendLn, pBuffer);
int lclStatus = send(ServerSock,
pBuffer,
sendLn,
0
);
if (0==i) // First send?
free(pBuffer); // Free buffer.
if (SOCKET_ERROR==lclStatus)
{
printf(JAProgNm ": Sending data #%d to the server failed. Error = %d\n", i, WSAGetLastError());
}
else
{
// printf(JAProgNm ": Sent %d bytes to the server\n", lclStatus);
}
} // End 'for' Send loop.
DoShutdown:
// Disable sending on ServerSock.
shutdown(ServerSock, SD_SEND);
for (;;)
{
// Receive data from the server socket.
rcRecv = recv(ServerSock, szClientA, sizeof(szClientA), 0);
// Check if there is any data received. If there is, display it.
if (SOCKET_ERROR==rcRecv)
{
printf(JAProgNm ": No data is received, recv failed. Error = %d\n", WSAGetLastError());
break;
}
else if (0==rcRecv)
{
printf("\n\n" JAProgNm ": Finished receiving data. Total received = %d\n", TotalRecvd);
break;
}
else
{
TotalRecvd += rcRecv; // Accumulate running total.
#define ServerMsgArraySz 10
// It is assumed -- but not checked -- that in each receive there is at least 1 string and
// that the total number of strings sent across receives does not exceed ServerMsgArraySz.
char * pSvrMsg[ServerMsgArraySz];
int msgCt = 0;
BOOLEAN bFindNextStr = TRUE;
// Find strings (there may be more than one in the received data).
for (int charIdx = 0; charIdx < rcRecv; charIdx ++)
{
if (TRUE==bFirst) // First string?
{
charIdx += sizeof(ULONG); // Bump past total byte count.
bFirst = FALSE; // Turn flag off.
}
if (TRUE==bFindNextStr) // Looking for a string?
if (0!=szClientA[charIdx]) // Is current byte not 0?
{
msgCt++; // Bump string count.
pSvrMsg[msgCt-1] = &szClientA[charIdx]; // Point to current string.
bFindNextStr = FALSE; // Remember now not looking for a string.
}
else
;
else // Handling a string.
if (0==szClientA[charIdx]) // Is current byte 0?
bFindNextStr = TRUE; // Remember now looking for a string.
else
;
}
for (int msgIdx = 0; msgIdx < msgCt; msgIdx ++)
// Display the string(s) received from the server.
printf(JAProgNm ": Received from server = \n ***>>>%s<<<***\n", pSvrMsg[msgIdx]);
}
}
// Disable receiving on ServerSock.
shutdown(ServerSock, SD_RECEIVE);
// Close the socket.
closesocket(ServerSock);
WSACleanup();
ExitPoint:
return 0;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -