1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef NET_BASE_TOOLS_HTTP_LISTEN_SOCKET_H_ 6 #define NET_BASE_TOOLS_HTTP_LISTEN_SOCKET_H_ 7 #pragma once 8 9 #include "base/message_loop.h" 10 #include "net/base/listen_socket.h" 11 12 class HttpServerRequestInfo; 13 class HttpServerResponseInfo; 14 15 // Implements a simple HTTP listen socket on top of the raw socket interface. 16 class HttpListenSocket : public ListenSocket, 17 public ListenSocket::ListenSocketDelegate { 18 public: 19 class Delegate { 20 public: 21 virtual void OnRequest(HttpListenSocket* connection, 22 HttpServerRequestInfo* info) = 0; 23 24 protected: 25 virtual ~Delegate() {} 26 }; 27 28 static HttpListenSocket* Listen(const std::string& ip, int port, 29 HttpListenSocket::Delegate* delegate); 30 31 virtual void Listen(); 32 virtual void Accept(); 33 34 // Send a server response. 35 // TODO(mbelshe): make this capable of non-ascii data. 36 void Respond(HttpServerResponseInfo* info, std::string& data); 37 38 // ListenSocketDelegate 39 virtual void DidAccept(ListenSocket* server, ListenSocket* connection); 40 virtual void DidRead(ListenSocket* connection, const char* data, int len); 41 virtual void DidClose(ListenSocket* sock); 42 43 private: 44 friend class base::RefCountedThreadSafe<ListenSocket>; 45 46 static const int kReadBufSize = 16 * 1024; 47 HttpListenSocket(SOCKET s, HttpListenSocket::Delegate* del); 48 virtual ~HttpListenSocket(); 49 50 // Expects the raw data to be stored in recv_data_. If parsing is successful, 51 // will remove the data parsed from recv_data_, leaving only the unused 52 // recv data. 53 HttpServerRequestInfo* ParseHeaders(); 54 55 HttpListenSocket::Delegate* delegate_; 56 std::string recv_data_; 57 58 DISALLOW_COPY_AND_ASSIGN(HttpListenSocket); 59 }; 60 61 #endif // NET_BASE_TOOLS_HTTP_LISTEN_SOCKET_H_ 62