Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // FileServer.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include "stdio.h"
- #include "conio.h"
- #include "winsock2.h"
- #include "ws2tcpip.h"
- struct Client
- {
- SOCKET c;
- SOCKADDR_IN cAddr;
- };
- SOCKET s;
- SOCKADDR_IN sAddr;
- int nClient = 0;
- Client *fClient[1024];
- DWORD WINAPI ReceiverThread(LPVOID Param) {
- int i = (int)Param;
- int j = 0;
- int len;
- int filesize = 0;
- char buf[1024];
- char msg[1024];
- printf("Client %d da ket noi.\n", i);
- while (true) {
- len = recv(fClient[i]->c, buf, 1024, 0);
- if (len > 0) {
- buf[len-1] = 0;
- if (strnicmp(buf, "GET ", 4) == 0) {
- char filename[100];
- memcpy(filename, &buf[4], strlen(buf) - 4);
- filename[strlen(buf) - 4] = 0;
- FILE *fp = fopen(filename, "rb");
- if (fp != NULL) {
- fseek(fp, 0, SEEK_END);
- filesize = ftell(fp);
- fseek(fp, 0, SEEK_END);
- sprintf(msg, "%d", filesize);
- send(fClient[i]->c, msg, strlen(msg), 0);
- rewind(fp);
- int checksize = 0;
- char* buffer;
- buffer = (char*)malloc(4096);
- while (checksize < filesize) {
- int Read = fread_s(buffer, 4096, sizeof(char), 4096, fp);
- int Sent = send(fClient[i]->c, buffer, Read, 0);
- checksize += Sent;
- }
- }
- else {
- send(fClient[i]->c, "FAILED file not found.\n", sizeof("FAILED file not found.\n"), 0);
- }
- }
- else {
- send(fClient[i]->c, "FAILED Unknown command.\n", sizeof("FAILED Unknown command.\n"), 0);
- }
- }
- }
- return 0;
- }
- int main()
- {
- WSADATA wsadata;
- int ret = WSAStartup(MAKEWORD(2, 2), &wsadata);
- s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- sAddr.sin_family = AF_INET;
- sAddr.sin_addr.s_addr = ntohs(INADDR_ANY);
- sAddr.sin_port = htons(10008);
- ret = bind(s, (sockaddr*)&sAddr, sizeof(sAddr));
- ret = listen(s, 16);
- printf("Waiting for client...\n");
- int clientlen = sizeof(SOCKADDR_IN);
- int i;
- bool tachluong = false;
- for (i = 0; i < 1024; i++) fClient[i] = 0;
- while (true) {
- for (i = 0; i < nClient; i++)
- if (fClient[i] == 0) break;
- fClient[i] = new Client;
- fClient[i]->c = accept(s, (sockaddr*)&fClient[i]->cAddr, &clientlen);
- CreateThread(0, 0, ReceiverThread, (LPVOID)i, 0, 0);
- if (i == nClient) nClient++;
- }
- closesocket(s);
- WSACleanup();
- getch();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement