1 // Copyright (c) 2012 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 CHROME_TEST_CHROMEDRIVER_NET_WEBSOCKET_H_ 6 #define CHROME_TEST_CHROMEDRIVER_NET_WEBSOCKET_H_ 7 8 #include <string> 9 10 #include "base/basictypes.h" 11 #include "base/compiler_specific.h" 12 #include "base/memory/ref_counted.h" 13 #include "base/threading/thread_checker.h" 14 #include "net/base/completion_callback.h" 15 #include "net/socket/tcp_client_socket.h" 16 #include "net/websockets/websocket_frame_parser.h" 17 #include "url/gurl.h" 18 19 namespace net { 20 class DrainableIOBuffer; 21 class IOBufferWithSize; 22 } 23 24 class WebSocketListener; 25 26 // A text-only, non-thread safe WebSocket. Must be created and used on a single 27 // thread. Intended particularly for use with net::HttpServer. 28 class WebSocket { 29 public: 30 // |url| must be an IP v4/v6 literal, not a host name. 31 WebSocket(const GURL& url, WebSocketListener* listener); 32 virtual ~WebSocket(); 33 34 // Initializes the WebSocket connection. Invokes the given callback with 35 // a net::Error. May only be called once. 36 void Connect(const net::CompletionCallback& callback); 37 38 // Sends the given message and returns true on success. 39 bool Send(const std::string& message); 40 41 private: 42 enum State { 43 INITIALIZED, 44 CONNECTING, 45 OPEN, 46 CLOSED 47 }; 48 49 void OnSocketConnect(int code); 50 51 void Write(const std::string& data); 52 void OnWrite(int code); 53 void ContinueWritingIfNecessary(); 54 55 void Read(); 56 void OnRead(int code); 57 void OnReadDuringHandshake(const char* data, int len); 58 void OnReadDuringOpen(const char* data, int len); 59 60 void InvokeConnectCallback(int code); 61 void Close(int code); 62 63 base::ThreadChecker thread_checker_; 64 65 GURL url_; 66 WebSocketListener* listener_; 67 State state_; 68 scoped_ptr<net::TCPClientSocket> socket_; 69 70 net::CompletionCallback connect_callback_; 71 std::string sec_key_; 72 std::string handshake_response_; 73 74 scoped_refptr<net::DrainableIOBuffer> write_buffer_; 75 std::string pending_write_; 76 77 scoped_refptr<net::IOBufferWithSize> read_buffer_; 78 net::WebSocketFrameParser parser_; 79 std::string next_message_; 80 81 DISALLOW_COPY_AND_ASSIGN(WebSocket); 82 }; 83 84 // Listens for WebSocket messages and disconnects on the same thread as the 85 // WebSocket. 86 class WebSocketListener { 87 public: 88 virtual ~WebSocketListener() {} 89 90 // Called when a WebSocket message is received. 91 virtual void OnMessageReceived(const std::string& message) = 0; 92 93 // Called when the WebSocket connection closes. Will be called at most once. 94 // Will not be called if the connection was never established or if the close 95 // was initiated by the client. 96 virtual void OnClose() = 0; 97 }; 98 99 #endif // CHROME_TEST_CHROMEDRIVER_NET_WEBSOCKET_H_ 100