|
[code:1]#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#define CR '\r'
#define LF '\n'
#define PORT 6001
#define MAX 4096
int http_get ;
#if 0
char * GetLine(int fd)
{
char netread[MAX], readch;
ssize_t n;
int len;
len=0;
netread[0]=CR;
netread[1]=LF;
while(len<MAX) {
n=read(fd,&readch, 1);
if(n<=0 ) break;
netread[len++] =readch;
if (readch ==LF ) break;
}
netread[len]='\0';
return netread;
}
#endif
int HandleMsgs(char*s)
{
if (s[0] ==CR && s[1]==LF ) return -1;
else if (strncmp(s,"GET",3) ==0)
http_get=1;
return 0;
}
int main(int argc, char *argv[])
{
int sockfd;
int client_sockfd, len, r;
char msg[MAX];
struct sockaddr_in sever_addr;
struct sockaddr_in client_addr;
sockfd=socket(AF_INET, SOCK_STREAM,0);
if(sockfd ==-1)
{
perror(NULL);
exit(1);
}
sever_addr.sin_family=AF_INET;
sever_addr.sin_addr.s_addr=htonl(INADDR_ANY);
sever_addr.sin_port =htons(PORT);
if (bind (sockfd,(sockaddr*)&sever_addr, sizeof(struct sockaddr_in) )<0 )
{
perror(NULL);
exit(1);
}
while(1)
{
listen(sockfd, 25);
len=sizeof(struct sockaddr_in);
client_sockfd= accept(sockfd, (sockaddr*)&client_addr,(socklen_t*)&len);
if (client_sockfd ==-1) {
perror(NULL);
exit(1);
}
r=0;
http_get=0;
while(r!=-1)
{
char netread[MAX], readch;
ssize_t n;
int len;
len=0;
netread[0]=CR;
netread[1]=LF;
while(len<MAX) {
n=read(sockfd,&readch, 1);
if(n<=0 ) break;
netread[len++] =readch;
if (readch ==LF ) break;
}
netread[len]='\0';
strcpy(msg, netread);
//strcpy(msg, GetLine(client_sockfd) );
r=HandleMsgs(msg);
printf("%s\n",msg);
}
if (http_get ){
printf("[Response to client .]\n");
write(client_sockfd, "<HTML>\n",7);
write(client_sockfd, "<H3>HELLO!</H3>\n",16);
write(client_sockfd, "</HTML>\n\n",8);
write(client_sockfd, '\0',1);
}
close(client_sockfd);
}
运行此程序,
在浏览器窗口中 输入 http://127.0.0.1:6001 ,没反映,一直没出现应该出现的 HELLO ,运行此程序的终端窗口也有反映,但什么都
没有出现,变成空白的,不知怎么回事?
[/code:1] |
|