-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnection.cpp
More file actions
50 lines (49 loc) · 2.21 KB
/
Connection.cpp
File metadata and controls
50 lines (49 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "Connection.h"
//Constructor: Call parent Thread Constructor
Connection::Connection(TCPSocket * p_tcpSocket): Thread()
{
tcpSocket = p_tcpSocket; // Set the TCP socket
next_connection = NULL; // Set the next pointer to NULL
}
void * Connection::threadMainBody (void * arg)
{
char file_name[1024]; // A buffer for holding the file name
memset (file_name,0,1024); // Initialize the buffer
// read from socket the file name to be fetched
int read_bytes = tcpSocket->readFromSocket(file_name,1023);
if ( read_bytes > 0) // If read successfully
{
// Clean up file name
if ( file_name[strlen(file_name)-1] == '\n' || file_name[strlen(file_name)-1] == '\r')
file_name[strlen(file_name)-1] = 0;
if ( file_name[strlen(file_name)-1] == '\n' || file_name[strlen(file_name)-1] == '\r')
file_name[strlen(file_name)-1] = 0;
FILE * f = fopen(file_name,"r"); // Try to open the file
if ( f != NULL) // If opened
{
fseek (f,0,2); // Seek to the end of the file
long fsize = ftell(f); // Get current location which represents the size
// Allocate a buffer with the file size to read the content
char * buffer = (char *) calloc(fsize+1,sizeof(char));
fseek (f,0,0); // Seek the beginning of the file
fread(buffer,1,fsize,f); // Read the whole file into the buffer
tcpSocket->writeToSocket(buffer,fsize); // Write the buffer to the socket
free(buffer); // Free the buffer
fclose(f); // Close the file
}
else
{
perror("Error With File\n"); // Print an error message
tcpSocket->writeToSocket("Error\n",6);// Write error to the socket
}
}
// Shutdown the TCP Socket
tcpSocket->shutDown();
return NULL;
}
// A modifier that sets the pointer of the next connection
void Connection::setNextConnection(Connection * connection){next_connection = connection;}
// A Selectot that returned a pointer to the next connection
Connection * Connection::getNextConnection (){return next_connection;}
// Destructor: delete the TCP socket if set
Connection::~Connection(){if ( tcpSocket != NULL ) delete (tcpSocket);}