blob: 098be337b1eab49c4927da42d0b8bd46366dcca5 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/base/socket_reader.h"
#include "base/compiler_specific.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/socket/socket.h"
namespace remoting {
namespace {
int kReadBufferSize = 4096;
} // namespace
SocketReader::SocketReader()
: socket_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
}
SocketReader::~SocketReader() {
}
void SocketReader::Init(net::Socket* socket,
ReadResultCallback read_result_callback) {
DCHECK(socket);
DCHECK(!socket_);
socket_ = socket;
read_result_callback_ = read_result_callback;
DoRead();
}
void SocketReader::DoRead() {
while (true) {
read_buffer_ = new net::IOBuffer(kReadBufferSize);
int result = socket_->Read(
read_buffer_, kReadBufferSize, base::Bind(&SocketReader::OnRead,
weak_factory_.GetWeakPtr()));
HandleReadResult(result);
if (result <= 0)
break;
}
}
void SocketReader::OnRead(int result) {
HandleReadResult(result);
if (result > 0)
DoRead();
}
void SocketReader::HandleReadResult(int result) {
if (result != net::ERR_IO_PENDING) {
if (result < 0)
read_buffer_ = NULL;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&SocketReader::CallCallback, weak_factory_.GetWeakPtr(),
read_buffer_, result));
}
}
void SocketReader::CallCallback(scoped_refptr<net::IOBuffer> data, int result) {
read_result_callback_.Run(data, result);
}
} // namespace remoting
|