关闭

socket文件接收

标签: socket
37人阅读 评论(0) 收藏 举报
分类:
// 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;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:466次
    • 积分:20
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:4篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档