Hi there I'm currently working on a Multi Threaded webserver.
So far I have manged to set up the webserver on an infinate loop waiting for a request at the socket.
This is where it gets abit weird, Yesterday I managed to find an example of reading a html code into a buffer then sending that buffer to the a browser and it would display fine.
However I have then tried to Implement the multi thread with the CreateThread function, unfortunalty I was unable to fully understand.. but when I tried to go back to just my single threaded webserver its not working now... I have no idea why after hours of fiddling around with stuff have now decided to look for some help.
Here is my code... any help would be greatly appreciated. I have commented fairly well so that should help you understand what I'm working towards.
Code:#include <stdio.h> #include <stdlib.h> #include <winsock.h> int main() { int s,n; unsigned fd; struct sockaddr sin={AF_INET,{31,144,0,0,0,0,0,0,0,0,0,0,0,0}}; WSADATA wsaData; char *header="HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"; char data[512]; char filename[256]; FILE *f; WSAStartup(MAKEWORD(1, 1), &wsaData); // initialise windows sockets s=socket(PF_INET,SOCK_STREAM, 0); // create a socket bind(s,&sin, sizeof(sin)); // bind it to port 80 listen(s,10); // allow up to 10 incoming connections while(1) { fd=accept(s,NULL,NULL); // wait for a request n=recv(fd,data,512,0); // recieve the request using fd data[n]=0; // NUL terminate it sscanf(data,"GET /%s ",filename); // get the name of the file f=fopen(filename,"rb"); // open the file (might be binary) send(fd,header,strlen(header),0); // send the header // //file size long lSize; fseek (f,0,SEEK_END); lSize = ftell(f); rewind(f); // allocate memory char *buffer; buffer = (char*)malloc(sizeof(char)*lSize); if (buffer == NULL){ fputs ("Read error",stderr); exit(1); } //copy file to buffer size_t result; result = fread(buffer,1,lSize,f); if (result != lSize){ fputs("Read error",stderr); exit(2); } //send buffer content to browser send(fd,buffer,strlen(buffer),0); // closesocket(fd); // close the socket fclose(f); //close file free (buffer); //empty buffer return 0; // send the file // //closesocket(fd); // close the socket } }



LinkBack URL
About LinkBacks


