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 #include "remoting/protocol/message_reader.h"
8 #include "base/callback.h"
9 #include "base/compiler_specific.h"
10 #include "base/location.h"
11 #include "base/thread_task_runner_handle.h"
12 #include "base/single_thread_task_runner.h"
13 #include "net/base/io_buffer.h"
14 #include "net/base/net_errors.h"
15 #include "net/socket/socket.h"
16 #include "remoting/base/compound_buffer.h"
17 #include "remoting/proto/internal.pb.h"
22 static const int kReadBufferSize
= 4096;
24 MessageReader::MessageReader()
32 MessageReader::~MessageReader() {
35 void MessageReader::SetMessageReceivedCallback(
36 const MessageReceivedCallback
& callback
) {
37 DCHECK(CalledOnValidThread());
38 message_received_callback_
= callback
;
41 void MessageReader::StartReading(net::Socket
* socket
) {
42 DCHECK(CalledOnValidThread());
48 void MessageReader::DoRead() {
49 DCHECK(CalledOnValidThread());
50 // Don't try to read again if there is another read pending or we
51 // have messages that we haven't finished processing yet.
52 while (!closed_
&& !read_pending_
&& pending_messages_
== 0) {
53 read_buffer_
= new net::IOBuffer(kReadBufferSize
);
54 int result
= socket_
->Read(
57 base::Bind(&MessageReader::OnRead
, weak_factory_
.GetWeakPtr()));
58 HandleReadResult(result
);
62 void MessageReader::OnRead(int result
) {
63 DCHECK(CalledOnValidThread());
64 DCHECK(read_pending_
);
65 read_pending_
= false;
68 HandleReadResult(result
);
73 void MessageReader::HandleReadResult(int result
) {
74 DCHECK(CalledOnValidThread());
79 OnDataReceived(read_buffer_
.get(), result
);
80 } else if (result
== net::ERR_IO_PENDING
) {
83 if (result
!= net::ERR_CONNECTION_CLOSED
) {
84 LOG(ERROR
) << "Read() returned error " << result
;
86 // Stop reading after any error.
91 void MessageReader::OnDataReceived(net::IOBuffer
* data
, int data_size
) {
92 DCHECK(CalledOnValidThread());
93 message_decoder_
.AddData(data
, data_size
);
95 // Get list of all new messages first, and then call the callback
98 CompoundBuffer
* buffer
= message_decoder_
.GetNextMessage();
102 base::ThreadTaskRunnerHandle::Get()->PostTask(
104 base::Bind(&MessageReader::RunCallback
,
105 weak_factory_
.GetWeakPtr(),
106 base::Passed(make_scoped_ptr(buffer
))));
110 void MessageReader::RunCallback(scoped_ptr
<CompoundBuffer
> message
) {
111 if (!message_received_callback_
.is_null()){
112 message_received_callback_
.Run(
114 base::Bind(&MessageReader::OnMessageDone
, weak_factory_
.GetWeakPtr()));
118 void MessageReader::OnMessageDone() {
119 DCHECK(CalledOnValidThread());
121 DCHECK_GE(pending_messages_
, 0);
123 // Start next read if necessary.
127 } // namespace protocol
128 } // namespace remoting