#pragma once #include "HttpAnalysis.h" #include "Json.h" #include "SocketC.h" SocketC tcpc(1); char* U8ToUnicode(char* szU8) { //UTF8 to Unicode //预转换,得到所需空间的大小 int wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL, szU8, strlen(szU8), NULL, 0); //分配空间要给'\0'留个空间,MultiByteToWideChar不会给'\0'空间 wchar_t* wszString = new wchar_t[wcsLen + 1]; //转换 ::MultiByteToWideChar(CP_UTF8, NULL, szU8, strlen(szU8), wszString, wcsLen); //最后加上'\0' wszString[wcsLen] = '\0'; char* m_char; int len = WideCharToMultiByte(CP_ACP, 0, wszString, wcslen(wszString), NULL, 0, NULL, NULL); m_char = new char[len + 1]; WideCharToMultiByte(CP_ACP, 0, wszString, wcslen(wszString), m_char, len, NULL, NULL); m_char[len] = '\0'; return m_char; } void OutStr(string strSrc) { int nwLen = ::MultiByteToWideChar(CP_ACP, 0, strSrc.c_str(), -1, NULL, 0); wchar_t* pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴 ZeroMemory(pwBuf, nwLen * 2 + 2); ::MultiByteToWideChar(CP_ACP, 0, strSrc.c_str(), strSrc.length(), pwBuf, nwLen); int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL); char* pBuf = new char[nLen + 1]; ZeroMemory(pBuf, nLen + 1); ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL); std::string retStr(pBuf); delete[]pwBuf; delete[]pBuf; pwBuf = NULL; pBuf = NULL; cout << retStr; } BOOL b = FALSE; void recvFunc(char* buf, int len) { OutStr(buf); //tcpc.Close(); b = TRUE; } //处理请求 VOID RecvRequest(CStringA data) { tcpc.SendStr(data.GetString()); for (int i = 0; i < 50; i++) { Sleep(100); if (b) return; } OutStr("{\"data\":\"服务器未响应\"}"); } int main(int argc, char** argv, char** envp) { //Sleep(10000); HttpAnalysis http(envp); //拿到环境变量以及网页需要获取的数据 CStringA Method; Method = http.HttpValue["REQUEST_METHOD"]; Method.MakeUpper(); cout << "Access-Control-Allow-Headers: Content-Type, api_key, Authorization\r\n"; cout << "Access-Control-Allow-Origin: *\r\n"; cout << "Content-Type:application/json\r\n\r\n"; //cout << "Content-Type: text/plain;charset=iso-8859-1\r\n\r\n"; //对接微信需要这个类型 CStringA data; string hdata; if (http.data != NULL) { hdata = U8ToUnicode(http.data); } Json json, tmp; if (tcpc.Connect("127.0.0.1", 6666)) { tcpc.SetRecvFunc(recvFunc); json[(CStringA)"Method"] = Method; if (Method == "POST") { json[(CStringA)"IP"] = (CStringA)http.HttpValue["REMOTE_ADDR"].GetString(); if (tmp.parse((CStringA)hdata.c_str()) != -1) { json[(CStringA)"Data"] = tmp; } else { json[(CStringA)"Data"] = (CStringA)hdata.c_str(); } RecvRequest(json.write()); return 0; } else { OutStr("{\"data\":\"该网页只POST方式提交数据\"}"); return 0; } } OutStr("{\"data\":\"服务器内部错误\"}"); }