Re-land: C++ readability review
[chromium-blink-merge.git] / remoting / protocol / message_reader.h
blob65d52d0a8bbe5cfb34965be2ef64eb982e8220e9
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 REMOTING_PROTOCOL_MESSAGE_READER_H_
6 #define REMOTING_PROTOCOL_MESSAGE_READER_H_
8 #include "base/callback.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/memory/weak_ptr.h"
11 #include "base/threading/non_thread_safe.h"
12 #include "remoting/base/compound_buffer.h"
13 #include "remoting/protocol/message_decoder.h"
15 namespace net {
16 class IOBuffer;
17 class Socket;
18 } // namespace net
20 namespace remoting {
21 namespace protocol {
23 // MessageReader reads data from the socket asynchronously and calls
24 // callback for each message it receives. It stops calling the
25 // callback as soon as the socket is closed, so the socket should
26 // always be closed before the callback handler is destroyed.
28 // In order to throttle the stream, MessageReader doesn't try to read
29 // new data from the socket until all previously received messages are
30 // processed by the receiver (|done_task| is called for each message).
31 // It is still possible that the MessageReceivedCallback is called
32 // twice (so that there is more than one outstanding message),
33 // e.g. when we the sender sends multiple messages in one TCP packet.
34 class MessageReader : public base::NonThreadSafe {
35 public:
36 typedef base::Callback<void(scoped_ptr<CompoundBuffer>, const base::Closure&)>
37 MessageReceivedCallback;
39 MessageReader();
40 virtual ~MessageReader();
42 // Sets the callback to be called for each incoming message.
43 void SetMessageReceivedCallback(const MessageReceivedCallback& callback);
45 // Starts reading from |socket|.
46 void StartReading(net::Socket* socket);
48 private:
49 void DoRead();
50 void OnRead(int result);
51 void HandleReadResult(int result);
52 void OnDataReceived(net::IOBuffer* data, int data_size);
53 void RunCallback(scoped_ptr<CompoundBuffer> message);
54 void OnMessageDone();
56 net::Socket* socket_;
58 // Set to true, when we have a socket read pending, and expecting
59 // OnRead() to be called when new data is received.
60 bool read_pending_;
62 // Number of messages that we received, but haven't finished
63 // processing yet, i.e. |done_task| hasn't been called for these
64 // messages.
65 int pending_messages_;
67 bool closed_;
68 scoped_refptr<net::IOBuffer> read_buffer_;
70 MessageDecoder message_decoder_;
72 // Callback is called when a message is received.
73 MessageReceivedCallback message_received_callback_;
75 base::WeakPtrFactory<MessageReader> weak_factory_;
77 DISALLOW_COPY_AND_ASSIGN(MessageReader);
80 } // namespace protocol
81 } // namespace remoting
83 #endif // REMOTING_PROTOCOL_MESSAGE_READER_H_