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.
5 #ifndef CHROME_TEST_CHROMEDRIVER_NET_WEBSOCKET_H_
6 #define CHROME_TEST_CHROMEDRIVER_NET_WEBSOCKET_H_
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"
20 class DrainableIOBuffer
;
21 class IOBufferWithSize
;
24 class WebSocketListener
;
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.
30 // |url| must be an IP v4/v6 literal, not a host name.
31 WebSocket(const GURL
& url
, WebSocketListener
* listener
);
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
);
38 // Sends the given message and returns true on success.
39 bool Send(const std::string
& message
);
49 void OnSocketConnect(int code
);
51 void Write(const std::string
& data
);
52 void OnWrite(int code
);
53 void ContinueWritingIfNecessary();
56 void OnRead(int code
);
57 void OnReadDuringHandshake(const char* data
, int len
);
58 void OnReadDuringOpen(const char* data
, int len
);
60 void InvokeConnectCallback(int code
);
63 base::ThreadChecker thread_checker_
;
66 WebSocketListener
* listener_
;
68 scoped_ptr
<net::TCPClientSocket
> socket_
;
70 net::CompletionCallback connect_callback_
;
72 std::string handshake_response_
;
74 scoped_refptr
<net::DrainableIOBuffer
> write_buffer_
;
75 std::string pending_write_
;
77 scoped_refptr
<net::IOBufferWithSize
> read_buffer_
;
78 net::WebSocketFrameParser parser_
;
79 std::string next_message_
;
81 DISALLOW_COPY_AND_ASSIGN(WebSocket
);
84 // Listens for WebSocket messages and disconnects on the same thread as the
86 class WebSocketListener
{
88 virtual ~WebSocketListener() {}
90 // Called when a WebSocket message is received.
91 virtual void OnMessageReceived(const std::string
& message
) = 0;
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;
99 #endif // CHROME_TEST_CHROMEDRIVER_NET_WEBSOCKET_H_