// picture_server.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdafx.h"
#include<iostream>
//#include"sock.h"
#include<winsock2.h>
#include<windows.h>
#include <string.h>
using namespace std;
#pragma comment( lib, "ws2_32.lib" ) //使用了静态连接库
#define MAX_LEN 524288//1048576// 1M
/*
enum
{
USER_CLIENT1 = 1,
USER_CLIENT2,
USER_CLIENT3,
USER_CLIENT4,
USER_CLIENT5,
USER_CLIENT6,
USER_DATA,
USER_PICTURE,
USER_REGISTER,
};
struct recvMsg
{
int cliNum;
int transType;
int tempVa;
int humVal;
int somkVal;
char picData[800];
int picDataLen;
BOOL picEnd;
};
*/
DWORD WINAPI Servicer(LPVOID param)
{
WSADATA wsaData;
int err;
err=WSAStartup(MAKEWORD(1,1),&wsaData);
if(err!=0)
cout<<int(LOBYTE(wsaData.wVersion))<<".yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"<<int(HIBYTE(wsaData.wVersion))<<endl;
//创建用于监听的套接字
SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);//本机地址
//cout<<htonl(INADDR_ANY)<<endl;
addrSrv.sin_family=AF_INET;//协议家族
addrSrv.sin_port=htons(6000);//端口号
//绑定套接字
bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));//第二个参数为要绑定的本机端口号及其地址等 端口与SOCKET绑定
listen(sockSrv,50);//5---flags 将套接字置为监听模式(服务器端)
SOCKADDR_IN addrClient;//客户端地址
int len=sizeof(SOCKADDR);
FILE* frec=fopen("D:\\2new.avi","wb");//D:\\new.jpg
if(frec==NULL)
{
printf("File open error!\n");
exit(1);
}
int recbytes = 0;
int count = 0;
int countrec=0;
while(1)//服务死循环
{
SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);//建立一个接收请求的套接字,用以与客户端打交道
char buf[MAX_LEN];
int rn;
/*
recvMsg mess;
while(1)
{
recv(sockConn, (char*)&mess, sizeof(recvMsg),0);
if(mess.transType == USER_PICTURE)
{
if( mess.picEnd != TRUE )
{
fwrite(mess.picData, 1, mess.picDataLen, frec);
std::cout<<"recving data"<<std::endl;
}
else
{
break;
}
}
}
*/
while(1)
{
rn=recv(sockConn,buf,MAX_LEN,0);//若无错误发生,recv()返回读入的字节数。如果连接已中止,返回0。
countrec++;
if(rn<0)
{
int aaa=1;
printf("Can't receive file!\n");
exit(1);
}
recbytes += rn;
//buf[rn]='\0';
if(rn!=0)
{
fwrite(buf,sizeof(char),rn,frec);
//printf("%s\n",buf);
count++;
}
else
{
printf("receive over.\n");
printf("count=%d\n",count);
printf("recvbytes = %d\n",recbytes);
cout<<"countrec= "<<countrec<<endl;
fclose(frec);
exit(1);
}
// printf("get file:%s\n",buf);
memset(buf,0,sizeof(buf));
}
//char recvBuf[256];
//接收数据
//recv(sockConn,recvBuf,256,0);//阻塞式等待客户端的请求的到来
//打印接收的数据
// cout<<recvBuf<<" from:"<<inet_ntoa(addrClient.sin_addr)<<endl;//inet_ntoa(addrClient.sin_addr)显示了客户请示的地址
int a;
closesocket(sockConn);
//
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
CreateThread(0,0,Servicer,0,0,0);//建立一个服务端线程
//while(1);//主线程死循环
SuspendThread(GetCurrentThread());
return 1;
//return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
前往页