话不多说直接上代码:
void handleAccept(int socket_fd)
{
char buf[1024] = { '\0' };
string cmd;
string filename;
recv(socket_fd, buf, sizeof(buf), 0);//1
stringstream sstream;//2
sstream << buf;
sstream >> cmd;
sstream >> filename;
cout << cmd << " " << filename << endl;
if (cmd=="GET")//3
{
ifstream file;
filename = filename.substr(1, filename.length() - 1);
file.open(filename ,ifstream::binary);//4
string head = "HTTP/1.0 200 OK\r\nContent - type:text/plain\r\n\r\n";//5
if (!file)
{
cout << "fail" << endl;
closesocket(socket_fd);
return;
}
if (filename.find(".html")!=string::npos|| filename.find(".htm")!=string::npos)
{
head = "HTTP/1.0 200 OK\r\nContent - type:text/html\r\n\r\n";
}
if (filename.find(".png")!=string::npos)
{
head = "HTTP/1.0 200 OK\r\nContent - type:image/png\r\n\r\n";
}
if (filename.find(".jpg")!=string::npos)
{
head = "HTTP/1.0 200 OK\r\nContent - type:image/jpg\r\n\r\n";
}
send(socket_fd, head.c_str(), strlen(head.c_str()), 0);
while (!file.eof())//6
{
char buf[1024];
memset(buf, 0, sizeof(buf));
file.read(buf,sizeof(buf)-1);
int n = file.gcount();
send(socket_fd, buf,n,0);//1
}
file.close();//7
}
closesocket(socket_fd);//7
}
1 recv(socket_fd, buf, sizeof(buf), 0)和send(socket_fd, buf,n,0);
recv用于接收从客户端发送来的消息,send用于向服务端发送消息
recv/send函数原型如下
int recv(SOCKET s,char FAR * buf,int len,int flags)/int send(SOCKET s,const char FAR * buf,int len,int flags);
第一个参数表示代表对方的socket,
第二个参数为接收读取的信息的字符串
第三个参数为该字符串的大小
第四个参数可以用来控制读写操作
该值可以为一下几种
0
MSG_DONTROUTE:不查找路由表/* send without using routing tables */
MSG_OOB:接受或发送带外数据 /* process out-of-band data */
MSG_PEEK:查看数据,并不从系统缓冲区移走数据/* peek at incoming message */
MSG_WAITALL :等待任何数据/* do not complete until packet is completely filled */
etc…
解释:
MSG_DONTROUTE:是send函数使用的标志.这个标志告诉IP协议.目的主机在本地网络上面,没有必要查找路由表.这个标志一般用网络诊断和路由程式里面。
MSG_OOB:表示能够接收和发送带外的数据.关于带外数据我们以后会解释的.
MSG_PEEK:是recv函数的使用标志,表示只是从系统缓冲区中读取内容,而不清除系统缓冲区的内容。这样下次读的时候,仍然是相同的内容。一般在有多个进程读写数据时能够使用这个标志。
MSG_WAITALL:是recv函数的使用标志,表示等到任何的信息到达时才返回。使用这个标志的时候recv 会一直阻塞,直到指定的条件满足,或是发生了错误。
1)当读到了指定的字节时,函数正常返回,返回值等于len
2)当读到了文档的结尾时,函数正常返回.返回值小于len
3)当操作发生错误时,返回-1,且配置错误为相应的错误号(errno)
其他的几个选项,但是我们实际上用的很少.