在C++程序中添加逻辑流程控制
_request; try { read(&http_request); } catch (EXCEPTION e) { break; } FILE file; fp = fopen(http_request.uri); if (fp == NULL) { write(fp); fclose(file); } else write(504); } socket.close(); delete this; } void read(HTTP_REQUEST* http_request) { read(&http_request.header); read(&http_request.body, &http_request.header); } void read(HTTP_REQUEST_HEADER* header) { …} void read(BYTE[]& body, HTTP_REQUEST_HEADER& header) { …} string read_line() { while (TRUE) { FLOW_WAIT (m_buffer += ) char* str = strchr(m_buffer, ''\n''); if (!str) continue; } string s(m_buffer, 0, str - m_buffer); memcpy(m_buffer, str); buf_avail -= str - m_buffer; return s; } BYTE[] read_bytes(int sz) { while (TRUE) { WAIT (m_buffer += ); if (m_buffer.length < sz) continue; } BYTE[] data = m_buffer.extract(0, sz); return data; } void write(FILE* fp) { int filesize = fp.size(); string header; header << "200 OK\r\nContent-Length: " << filesize << ";\r\n" <<"\r\n"; write(header.c_str(), header.size()); int szBulk; for (int i = 0; i < filesize; i += szBulk) { szBulk = min(filesize - i, 8192); data = fread(fp, szBulk); write(data, szBulk); } } void write(WORD error_status) { string header; header << error_status << " Error\r\n" <<"\r\n"; write(header.c_str(), header.size()); } void write(BYTE[] data, int len) { while (len > 0) { int ret = socket.write(data, len); if (ret > 0) { data += ret; len -= ret; } if (len) { WAIT (bWritable == TRUE); } } } void OnRead() { int avail = socket.avail(); m_buffer += socket.read(avail); } void OnWrite() { bWritable = TRUE; } void OnClose() { delete this; } }; main { Socket listen_socket; listen_socket.listen(http_port); socket_add(listen_socket, NULL); socket_loop(socket_callback); } void socket_callback(void* user_data, SOCKET s, int msg, int lParam, void* pParam) { switch (msg) { case READ: if (user_data == NULL) { SOCKET s2 = accept(s); Connection conn = new Connection(socket); socket_add(s2, conn); break; } ((Connection*)user_data)->OnRead(); break; case WRITE: ((Connection*)user_data)->OnWrite(); break; case EXCEPT: ((Connection*)user_data)->OnExcept(); break; } } 这涉及到两个新的原语:一个为FLOW_START,其创建了一个新的子过程;另一个为FLOW_WAIT,其告之系统何时将被调用以继续程序流程。例如,FLOW_WAIT(m_buffer += )意味着m_buffer的操作符+=被执行,FLOW_WAIT (bWritable = TRUE)意味着bWritable被设为TRUE。 逻辑流程VS线程 逻辑流程看起来像是虚拟线程,但它实际上运行在创建它的线程空间之内。尽管两者都有独立的进程堆栈,但逻辑流程的开销要小一些,且不用处理流程间的同步问题。 逻辑流程也能用于异常处理。例如,可添加类似如下的代码:
|
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |