vc6.0 使用socket模拟get

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq635968970/article/details/43318577
// test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
#include "windows.h"
#include "Winsock2.h"
using namespace std;

//utf8转gbk
char* ConvertUtf8ToGBK(LPCTSTR strUtf8) {
    int len=MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)strUtf8, -1, NULL,0);
    unsigned short * wszGBK = new unsigned short[len+1];
    memset(wszGBK, 0, len * 2 + 2);
    MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)strUtf8, -1, wszGBK, len);

    len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL); 
    char *szGBK=new char[len + 1];
    memset(szGBK, 0, len + 1);
    WideCharToMultiByte (CP_ACP, 0, wszGBK, -1, szGBK, len, NULL,NULL);

    strUtf8 = szGBK;
	return szGBK;
}
//gbk转utf8
char* ConvertGBKToUtf8(char* strGBK) {
    int len=MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, NULL,0);
    unsigned short * wszUtf8 = new unsigned short[len+1];
    memset(wszUtf8, 0, len * 2 + 2);
    MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, wszUtf8, len);

    len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL); 
    char *szUtf8=new char[len + 1];
    memset(szUtf8, 0, len + 1);
    WideCharToMultiByte (CP_UTF8, 0, wszUtf8, -1, szUtf8, len, NULL,NULL);

    strGBK = szUtf8;
	return szUtf8;
}
int main(int argc, char* argv[])
{
	//创建socket
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;
	err = WSAStartup(wVersionRequested, &wsaData);	
	if(err != 0){
		return 0;
	}
	SOCKET client = socket(AF_INET, SOCK_STREAM, 0);
	SOCKADDR_IN addSrv;
	addSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	addSrv.sin_family = AF_INET;
	addSrv.sin_port = htons(80);
	if( 0 != connect( client, (SOCKADDR*)&addSrv, sizeof(SOCKADDR))){
		WSACleanup();
		return 0;
	}
	//设置变量用于保存
	char recvBuf[1000] = {0};
	char *p = null;
	char sendBuf[1000] = {0};
	//-------------http协议头
	sprintf(
		 sendBuf, 
		 "%s\r\n%s\r\n%s\r\n%s\r\n%s\r\n\r\n", 
		 "GET http://127.0.0.1 HTTP/1.1",
		 "Content-Type: application/x-www-form-urlencoded",
		 "Accept: html/text",
		 "Host: 127.0.0.1",
		 "Connection: Close"
	);
	while (1)
	{
		if( SOCKET_ERROR == send(client, sendBuf, sizeof(sendBuf), 0)){
			printf("发送失败");
		}
		if(recv(client, recvBuf, sizeof(recvBuf), 0) != SOCKET_ERROR){
			p = ConvertUtf8ToGBK(recvBuf);
			printf("%s\n", p);
		}else{
			printf("没有数据");
		}
		Sleep(3000);
	}
	return 0;
}

;

效果:


猜你喜欢

转载自blog.csdn.net/qq635968970/article/details/43318577
今日推荐