Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Лабы / !lab2 / UDPServer / UDPServer

.cpp
Скачиваний:
16
Добавлен:
17.04.2013
Размер:
2.41 Кб
Скачать
#include "stdafx.h"
#include "UDPServer.h"
#include "crc.h"
#include "winsock2.h"
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>

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

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

CWinApp theApp;

DWORD CrcTable[256];

struct ackwnpckt
{
	u_short ind;
};

struct packet
{
	u_short reclen;
    u_short ind;
	DWORD CRC;
	BYTE buffer[1000];
};

int myrcv(SOCKET s,packet*a,u_short number,sockaddr_in* client_addr)
{
	sockaddr_in addr;
    int sz = sizeof(addr);
	ackwnpckt ack;

	while (1) {
		if (recvfrom(s,(char*)a,sizeof(packet),0,(sockaddr*)&addr,&sz)==-1)
			return -1;
		if (a->CRC != CalcCRC((char*)&a->buffer[0],1000,&CrcTable[0]))
			continue;
		ack.ind = a->ind;
		sendto(s,(char*)&ack,sizeof(ackwnpckt),0,(sockaddr*)&addr,sz);
		if (a->ind==number)
          break;
		if (a->ind == 0)
			return -2;
		
	}
	return 1;
}

int _tmain()
{
	WSADATA wsaData;
	SOCKET s;
	struct sockaddr_in client;
	int rc;
	CFile File;
	CString sWorkDir;
	CString sFileName;
		
	FillCRCTable(&CrcTable[0]);

	if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
    {
        printf("Failed to load Winsock!\n");
        return 1;
    }
	
	client.sin_family=AF_INET;
	client.sin_port=htons(5150);
	client.sin_addr.s_addr=htonl(INADDR_ANY);

	s=socket(AF_INET,SOCK_DGRAM,0);
	if (s == SOCKET_ERROR)
    {
        printf("socket() failed: %d\n", WSAGetLastError());
        return 1;
    }

	if(bind(s,(sockaddr*)&client,sizeof(client)) == SOCKET_ERROR)
	{
        printf("bind() failed: %d\n", WSAGetLastError());
        return 1;
    }
	
	cout<<"Enter work directory:";
	cin>>sWorkDir.GetBuffer(1024);
	
   	while (SetCurrentDirectory((LPCTSTR)sWorkDir)==0)
	{
		cout<<"Invalid directory"<<endl;
		return -1;	
	}

	cout<<"Enter destination name:";
	cin>>sFileName.GetBuffer(1024);
		
	if( !File.Open((LPCTSTR)sFileName, CFile::modeWrite |
           CFile::shareExclusive | CFile::modeCreate))
	{
		 cout<< "File could not be opened "  << "\n";
	}
    
	packet a;
	int number=1;
    cout<<"... Please wait ..."<<endl;
	do
	{
	   rc = myrcv(s,&a,number,&client);
	   number++;
	   File.Write(a.buffer,a.reclen);

	}  while (rc!=-2);
	File.Close();
    cout<<"Downloading completed successful"<<endl;
	return 0;
}

Соседние файлы в папке UDPServer