Benutzerkonto
|
Sunday Webserver
Der Sunday Webserver ist ein kleiner multithreaded Webserver, den ich an einem langweiligen Sonntagnachmittag programmiert habe um die TCP/IP Programmierung zu lernen.
Im Moment ist seine einzige Funktion die Ausgabe einer einzigen Webseite, die statisch einkompiliert ist. Dank seiner multithre
aded Implementation kann er diese aber gleichzeitig an beliebig viele Clients senden.
Sunday Webserver Demopage
Kompilieren:
gcc -O3 -o sunday sunday.c -lpthread
/*
* Sunday Webserver 0.1.2
* (c) 2001 - 2006 by Stefan Heimers
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include
#include
#include // required for bind()
#include // listen
#include // for close
#include // for printf,...
#include
#include // strlen
#include
const char* seite="HTTP/1.1 200 OK\nDate: Sun, 30 Jul 2000 20:44:19 GMT\nServer: Sunday 0.1.2 (Unix) by Stefan Heimers\nLast-Modified: Fri, 10 Mar 2000 11:36:40 GMT\nETag: \"378ab-f6f-38c8de48\"\nAccept-Ranges: bytes\nContent-Length: 189\nConnection: close\nContent-Type: text/html\n\n\nSundaySunday Webserver 0.1.2 © by Stefan Heimers\n";
void serve(int socket)
{
int readsize;
int retval=0;
char buffer[5000];
readsize = recv(socket,buffer, 5000, 0);
buffer[readsize]='\0';
printf("received from client: %s\n",buffer);
send(socket,seite,strlen(seite),0);
close(socket);
pthread_exit(&retval);
}
int main()
{
int tcp_socket,accepted;
struct sockaddr_in my_addr;
socklen_t addrlen;
int bind_res;
pthread_t thread;
my_addr.sin_family=PF_INET;
my_addr.sin_port=htons(8085);
my_addr.sin_addr.s_addr=INADDR_ANY;
tcp_socket = socket(PF_INET, SOCK_STREAM, 0);
if (tcp_socket == -1)
perror("socket");
addrlen = sizeof(struct sockaddr);
bind_res = bind(tcp_socket,(struct sockaddr *)&my_addr,addrlen);
if (bind_res == -1)
perror("bind");
if (listen(tcp_socket,0) == -1 )
perror("listen");
while (1)
{
accepted = accept(tcp_socket,(struct sockaddr *)&my_addr,&addrlen);
if (accepted == -1)
perror("accept");
if ( pthread_create(&thread, NULL,(void *)serve,(void *) accepted) )
perror("error creating thread");
}
close(tcp_socket);
perror("close");
}
© 2002 by Stefan Heimers
|