OLD | NEW |
| (Empty) |
1 // Copyright 2015 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 #include "blimp/net/blimp_message_pump.h" | |
6 | |
7 #include "base/macros.h" | |
8 #include "blimp/common/logging.h" | |
9 #include "blimp/common/proto/blimp_message.pb.h" | |
10 #include "blimp/net/blimp_message_processor.h" | |
11 #include "blimp/net/common.h" | |
12 #include "blimp/net/connection_error_observer.h" | |
13 #include "blimp/net/packet_reader.h" | |
14 #include "net/base/io_buffer.h" | |
15 #include "net/base/net_errors.h" | |
16 | |
17 namespace blimp { | |
18 | |
19 BlimpMessagePump::BlimpMessagePump(PacketReader* reader) | |
20 : reader_(reader), buffer_(new net::GrowableIOBuffer), weak_factory_(this) { | |
21 DCHECK(reader_); | |
22 buffer_->SetCapacity(kMaxPacketPayloadSizeBytes); | |
23 } | |
24 | |
25 BlimpMessagePump::~BlimpMessagePump() {} | |
26 | |
27 void BlimpMessagePump::SetMessageProcessor(BlimpMessageProcessor* processor) { | |
28 DVLOG(1) << "SetMessageProcessor, processor=" << processor; | |
29 if (processor && !processor_) { | |
30 processor_ = processor; | |
31 ReadNextPacket(); | |
32 } else { | |
33 // Don't allow |processor_| to be cleared while there's a read inflight. | |
34 if (processor) { | |
35 DCHECK(!processor_ || !read_inflight_); | |
36 } | |
37 processor_ = processor; | |
38 } | |
39 } | |
40 | |
41 void BlimpMessagePump::ReadNextPacket() { | |
42 DVLOG(2) << "ReadNextPacket"; | |
43 DCHECK(processor_); | |
44 DCHECK(!read_inflight_); | |
45 read_inflight_ = true; | |
46 buffer_->set_offset(0); | |
47 reader_->ReadPacket(buffer_.get(), | |
48 base::Bind(&BlimpMessagePump::OnReadPacketComplete, | |
49 weak_factory_.GetWeakPtr())); | |
50 } | |
51 | |
52 void BlimpMessagePump::OnReadPacketComplete(int result) { | |
53 DVLOG(2) << "OnReadPacketComplete, result=" << result; | |
54 DCHECK(read_inflight_); | |
55 read_inflight_ = false; | |
56 if (result >= 0) { | |
57 std::unique_ptr<BlimpMessage> message(new BlimpMessage); | |
58 if (message->ParseFromArray(buffer_->data(), result)) { | |
59 VLOG(1) << "Received " << *message; | |
60 processor_->ProcessMessage( | |
61 std::move(message), | |
62 base::Bind(&BlimpMessagePump::OnProcessMessageComplete, | |
63 weak_factory_.GetWeakPtr())); | |
64 } else { | |
65 result = net::ERR_FAILED; | |
66 } | |
67 } | |
68 | |
69 if (result < 0) { | |
70 error_observer_->OnConnectionError(result); | |
71 } | |
72 } | |
73 | |
74 void BlimpMessagePump::OnProcessMessageComplete(int result) { | |
75 DVLOG(2) << "OnProcessMessageComplete, result=" << result; | |
76 | |
77 if (result < 0) { | |
78 error_observer_->OnConnectionError(result); | |
79 return; | |
80 } | |
81 | |
82 if (processor_) | |
83 ReadNextPacket(); | |
84 } | |
85 | |
86 } // namespace blimp | |
OLD | NEW |