WINSOCK 传送文件
SERVER:
// send_server.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <WinSock2.h> #include <stdio.h> #pragma comment(lib,"ws2_32.lib") int main(int argc,char** argv) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2),&wsadata) == -1) { printf("wsastartup error\r\n"); } SOCKET server; server = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (server == SOCKET_ERROR) { printf("server socket start error\r\n"); return 0; } sockaddr_in server_service; server_service.sin_family = AF_INET; server_service.sin_port = htons(8000); server_service.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); if (bind(server,(sockaddr*)&server_service,sizeof(server_service)) == SOCKET_ERROR) { printf("Bind Port error\r\n"); return 0; } if (listen(server,5) == SOCKET_ERROR) { printf("Listen client error\r\n"); return 0; } SOCKET acceptsocket; printf("wait accept recv data\r\n"); while (1) { acceptsocket = SOCKET_ERROR; while (acceptsocket == SOCKET_ERROR) { acceptsocket = accept(server,NULL,NULL); } printf("Client connetcd\r\n"); server = acceptsocket; break; } char sendbuf[1024] = {0}; DWORD dwread; BOOL bret; char filename[] = "test.exe"; HANDLE hfile = CreateFileA(filename,GENERIC_READ,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); while (true) { bret = ReadFile(hfile,sendbuf,1024,&dwread,NULL); if (bret == false) { printf("read file error\r\n"); break; } else if (dwread == 0) { printf("send file ok"); break; }else { send(server,sendbuf,dwread,0); } } CloseHandle(hfile); WSACleanup(); return 0; }
CLIENT:
// send_client.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <WinSock2.h> #pragma comment(lib,"ws2_32.lib") int main() { WSADATA wsadata; int iResult = WSAStartup(MAKEWORD(2,2),&wsadata); if (iResult != NO_ERROR) { printf("Errpr at wsastartup\r\n"); } SOCKET client; client = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (client == INVALID_SOCKET) { printf("error at socket():%ld\r\n",WSAGetLastError()); WSACleanup(); return 0; } sockaddr_in clientService; clientService.sin_family = AF_INET; clientService.sin_port = htons(8000); clientService.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); if (connect(client,(SOCKADDR*)&clientService,sizeof(clientService)) == SOCKET_ERROR) { printf("Faied to error\r\n"); WSACleanup(); return 0; } char recvbuf[1024] = {0}; int read; DWORD dwWrite; BOOL bRet; char filename[] = "test.exe"; HANDLE hfile = CreateFileA(filename,GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0); while (true) { read = recv(client,recvbuf,1024,0); if (read ==-1) { break; } bRet = WriteFile(hfile,recvbuf,read,&dwWrite,NULL); if (bRet == FALSE) { MessageBoxW(NULL,_T("Write buffer error\r\n"),NULL,MB_OK); } } MessageBoxW(NULL,_T("write buffer susccess\r\n"),NULL,MB_OK); return 0; }
在发送文件之前,我们可以利用getfilesize来获取文件打开的大小。