1. 程式人生 > >vc++ socket http協議post方法上傳 分塊上傳

vc++ socket http協議post方法上傳 分塊上傳

host www. UNC ket security mem packet 比較 content

分享一下我老師大神的人工智能教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智能的隊伍中來!http://www.captainbed.net

最近項目需要,通過C++客戶端向Web服務器用http協議上傳文件,網上介紹這方面的好像很少,所以做了個基礎的發上來供學習交流;
本人學c++沒幾天,代碼可能比較爛,大家湊合看吧。。
示例代碼:
1、C++ Clinet
[cpp] view plaincopy
#include "stdio.h"  
#include "WinSock2.h"  
#include "iostream"  
using namespace
std; #pragma comment(lib,"ws2_32.lib") long l_file_len; //獲取文件內容 bool file_con(char **buffer,LPCSTR file) { FILE *fp = fopen(file, "rb"); if(fp==NULL) { printf("文件上傳失敗,請檢查文件路徑.....\n"); return false; } fseek(fp, 0, SEEK_END); l_file_len = ftell(fp); rewind(fp); *buffer = new
char[l_file_len + 1]; memset(*buffer, 0, l_file_len + 1); fseek(fp, 0, SEEK_SET); fread(*buffer, sizeof(char), l_file_len, fp); fclose(fp); return true; } //文件上傳 std::string upload(LPCSTR lpszServer,LPCSTR lpszAddr,LPCSTR fileUrl) { char *file = NULL
; if(!file_con(&file,fileUrl)) { return "0"; } SOCKET sock = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock == INVALID_SOCKET) return "0"; SOCKADDR_IN server; server.sin_family = AF_INET; server.sin_port = htons(80); struct hostent *host_addr = gethostbyname(lpszServer); if (host_addr == NULL) return "host_addr == NULL"; server.sin_addr.s_addr = *((int *) *host_addr->h_addr_list); if (::connect(sock, (SOCKADDR *) &server, sizeof(SOCKADDR_IN)) == SOCKET_ERROR) { ::closesocket(sock); return "0"; } printf("ip address = %s, port = %d\n",inet_ntoa(server.sin_addr), ntohs(server.sin_port)); std::string header(""); std::string content(""); //----------------------post頭開始-------------------------------- header +="post "; header +=lpszAddr; header +=" HTTP/1.1\r\n"; header +="Host: "; header +=lpszServer; header += "\r\n"; header += "User-Agent: Mozilla/4.0\r\n"; header += "Connection: Keep-Alive\r\n"; header += "Accept: */*\r\n"; header += "Pragma: no-cache\r\n"; header += "Content-Type: multipart/form-data; charset=\"gb2312\"; boundary=----------------------------64b23e4066ed\r\n"; content += "------------------------------64b23e4066ed\r\n"; content += "Content-Disposition: form-data; name=\"file\"; filename=\"大論文和實驗材料.rar\"\r\n"; content += "Content-Type: aapplication/octet-stream\r\n\r\n"; //post尾時間戳 std::string strContent("\r\n------------------------------64b23e4066ed\r\n"); char temp[64] = {0}; //註意下面這個參數Content-Length,這個參數值是:http請求頭長度+請求尾長度+文件總長度 sprintf(temp, "Content-Length: %d\r\n\r\n", content.length()+l_file_len+strContent.length()); header += temp; std::string str_http_request; str_http_request.append(header).append(content); //----------------------post頭結束----------------------------------- //發送post頭 send(sock, str_http_request.c_str(), str_http_request.length(), 0); char fBuff[4096]; int nPacketBufferSize = 4096; // 每個數據包存放文件的buffer大小 int nStart;//記錄post初始位置 int nSize;//記錄剩余文件大小 // 就分塊傳送 for (int i = 0; i < l_file_len; i += nPacketBufferSize) { nStart=i; if (i + nPacketBufferSize + 1> l_file_len) { nSize = l_file_len - i; } else { nSize = nPacketBufferSize; } memcpy(fBuff, file + nStart, nSize); ::send(sock, fBuff, nSize, 0); Sleep(0.2); } ::send(sock,strContent.c_str(),strContent.length(),0); char szBuffer[1024] = {0}; while (true) { int nRet = ::recv(sock, szBuffer, sizeof(szBuffer), 0); if (nRet == 0 || nRet == WSAECONNRESET) { printf("Connection Closed.\n"); break; } else if (nRet == SOCKET_ERROR) { printf("socket error\n"); break; } else { printf("recv() returned %d bytes\n", nRet); printf("received: %s\n", szBuffer); break; } } ::closesocket(sock); delete [] file; return szBuffer; } void main() { WORD wVersionRequested=MAKEWORD(2,2); WSADATA wsaData; if(WSAStartup(wVersionRequested,&wsaData)) { cout<<"加載錯誤"<<endl; } if(LOBYTE(wsaData.wVersion)!=2||HIBYTE(wsaData.wHighVersion)!=2) { cout<<"WinSock‘s 加載錯誤"<<endl; } upload("localhost","/WebApplication1/Default.aspx","F:\\postgresql-8.3.3-2.rar"); } 2、Web Server [csharp] view plaincopy using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Text; namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Request.Files.Count > 0) { try { HttpPostedFile file = Request.Files[0]; string filePath = Request.PhysicalApplicationPath + file.FileName; file.SaveAs(filePath); Response.Write("Success\r\n"); } catch { Response.Write("Error\r\n"); } Response.End(); } } } } 上面就是簡單的代碼示例,web需配置iis,相信大家知道怎麽做^_^,還有一點就是web程序默認上傳文件的限制,默認上傳大小為4M,所以需要 在web.config中設置以下參數: [html] view plaincopy <httpRuntime maxRequestLength="951200" appRequestQueueLimit="60" executionTimeout="60"/> 這裏的maxRequestLength即是默認的上傳文件大小,單位是KB。

再分享一下我老師大神的人工智能教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智能的隊伍中來!http://www.captainbed.net

vc++ socket http協議post方法上傳 分塊上傳