Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <winsock2.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <string.h>
- #include <process.h>
- #include <windows.h>
- void fileReceive(void *param);
- HANDLE semaphore;
- HANDLE threadHandle;
- int main(int argc, char *argv[])
- {
- // Some stuff
- sock0 = socket(AF_INET, SOCK_STREAM, 0);
- if (sock0 == INVALID_SOCKET) {
- goto l_socket_error;
- }
- // associates a local address with a socket
- if (bind(sock0, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
- goto l_bind_error;
- }
- while (1) {
- // places a socket in a state in which it is listening for an incoming connection
- if (listen(sock0, 1) != 0) {
- goto l_socket_conn_setup_error;
- }
- len = sizeof(client);
- // The accept function permits an incoming connection attempt on a socket.
- sock = accept(sock0, (struct sockaddr *)&client, &len);
- if (sock == INVALID_SOCKET) {
- goto l_error_accpet;
- }
- semaphore = CreateSemaphore(0, 1, 1, 0);
- threadHandle = (HANDLE)_beginthread(&fileReceive, 0, &sock);
- if (threadHandle == 0) {
- printf("Thread handle error");
- return 1;
- }
- CloseHandle(semaphore);
- }
- WSACleanup();
- return 0;
- }
- void fileReceive(void *param) {
- int n = 0;
- int sock = *((int *)param);
- unsigned char buf[1];
- unsigned char buff[256] = { 0 };
- FILE *fp = NULL;
- memset(buff, 0, sizeof(buff));
- WaitForSingleObject(semaphore, INFINITE);
- // Receive file name
- int recvFile = recv(sock, buff, 255, 0);
- ReleaseSemaphore(semaphore, 1, 0);
- if ((recvFile == 0) || (recvFile == -1)) {
- goto l_recv_error;
- }
- fp = fopen(buff, "wb+");
- if (fp != NULL) {
- printf("file name (%s)n", buff);
- while (n = recv(sock, &buf[0], 1, 0) > 0) {
- size_t written = fwrite(&buf, sizeof(buf), 1, fp);
- if (written != 1) {
- goto l_write_error;
- }
- }
- printf("(%s) completen", buff);
- }
- else {
- goto l_fp_error;
- }
- fclose(fp);
- closesocket(sock);
- _endthread();
- CloseHandle(threadHandle);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement