socket文件接收

// Server.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include "windows.h"
#include <WinSock.h>
#include <iostream>


#pragma comment(lib, "ws2_32.lib")


using namespace std;
#define PORT 3574
#define IP_ADDRESS "10.3.15.11"


DWORD WINAPI ClientThread(LPVOID lpParameter)
{
SOCKET ClientSocket = (SOCKET)lpParameter;
int length = 0;
char buf[1024];
FILE * fDes = fopen("F:/3.MP3", "wb");
while((length = recv(ClientSocket, buf, sizeof(buf), 0))>0){   
if ( length == 0 || length == SOCKET_ERROR){
cout << "客户端退出!" << endl ;
break;
}
fwrite(buf, 1024, length, fDes);
printf("接收了%d字节!\n",length);
memset(buf, 0, 1025);
}
printf("文件传输成功!\n");
return 0;
}




int main(int argc, char * argv[])
{
WSADATA ws;
SOCKET ServerSocket, ClientSocket;
struct sockaddr_in LocalAddr, ClientAddr;
int Ret = 0;
int AddrLen = 0;
HANDLE hThread = NULL;


//初始化Windows端口
if (WSAStartup(MAKEWORD(2,2), &ws) != 0 )
{
cout << "初始化Windows Socket失败::" << GetLastError() << endl;
return -1;
}


//创建端口
ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ServerSocket == INVALID_SOCKET)
{
cout << "建立socket端口失败::" << GetLastError() << endl;
return -1;
}


LocalAddr.sin_family = AF_INET;
LocalAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS);
LocalAddr.sin_port = htons(PORT);
memset(LocalAddr.sin_zero, 0x00, 8);


//绑定端口
Ret = bind(ServerSocket, (struct sockaddr * )&LocalAddr, sizeof(LocalAddr));
if ( Ret != 0 )
{
cout << "绑定端口失败::" << GetLastError() << endl;
return -1;
}


Ret = listen(ServerSocket, 10);
if ( Ret !=0 )
{
cout << "监听端口失败::" << GetLastError() << endl;
return -1;
}

cout << "服务端已启动" << endl;


while(true)
{
AddrLen = sizeof(ClientAddr);
ClientSocket = accept(ServerSocket, (struct sockaddr *)&ClientAddr, &AddrLen);
if ( ClientSocket == INVALID_SOCKET)
{
cout << "Accept失败::" << GetLastError() << endl;
break;
}
cout << "Accept成功::"<< endl;


cout << "客户端连接::" << inet_ntoa(ClientAddr.sin_addr) << ":" << ClientAddr.sin_port << endl;
hThread = CreateThread(NULL, 0, ClientThread, (LPVOID)ClientSocket, 0, NULL);
if ( hThread == NULL )
{
cout << "建立线程失败!" << endl;
break;
}


CloseHandle(hThread);
}


closesocket(ServerSocket);
closesocket(ClientSocket);
WSACleanup();


return 0;
}

阅读更多
文章标签: socket
个人分类: socket
想对作者说点什么? 我来说一句

Linux 先socket 通信服务端

2014年07月04日 4KB 下载

Qt5-TCPsocket文件传送接收

2017年04月04日 19KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭