1 // Copyright 2014 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 "components/devtools_bridge/socket_tunnel_connection.h"
9 #include "net/base/io_buffer.h"
10 #include "net/base/net_errors.h"
11 #include "net/socket/stream_socket.h"
13 namespace devtools_bridge
{
15 SocketTunnelConnection::SocketTunnelConnection(int index
) : index_(index
) {
18 SocketTunnelConnection::~SocketTunnelConnection() {
21 void SocketTunnelConnection::Write(scoped_refptr
<net::IOBufferWithSize
> chunk
) {
22 // TODO(serya): While it is unlikely (socket normally much faster than
23 // data channel) we should disconnect if too much data buffered.
24 buffer_
.push_back(chunk
);
25 if (buffer_
.size() == 1) {
26 current_
= new net::DrainableIOBuffer(chunk
.get(), chunk
->size());
31 void SocketTunnelConnection::BuildControlPacket(char* buffer
,
33 static_assert(kControlPacketSizeBytes
== 3,
34 "kControlPacketSizeBytes should equal 3");
35 buffer
[0] = kControlConnectionId
;
37 buffer
[2] = index_
+ kMinConnectionId
;
40 void SocketTunnelConnection::WriteCurrent() {
42 while(current_
->BytesRemaining() > 0) {
43 int result
= socket()->Write(current_
.get(), current_
->BytesRemaining(),
44 base::Bind(&SocketTunnelConnection::OnWriteComplete
,
45 base::Unretained(this)));
47 current_
->DidConsume(result
);
53 return; // Stop writing.
55 net::IOBufferWithSize
* chunk
= buffer_
.front().get();
56 current_
= new net::DrainableIOBuffer(chunk
, chunk
->size());
60 void SocketTunnelConnection::OnWriteComplete(int result
) {
62 current_
->DidConsume(result
);
67 void SocketTunnelConnection::ReadNextChunk() {
68 if (!read_buffer_
.get()) {
69 read_buffer_
= new net::GrowableIOBuffer();
70 read_buffer_
->SetCapacity(kMaxPacketSizeBytes
);
72 // Header of the data packet.
73 *read_buffer_
->StartOfBuffer() = index_
+ kMinConnectionId
;
74 read_buffer_
->set_offset(1);
76 int result
= socket()->Read(
78 read_buffer_
->RemainingCapacity(),
79 base::Bind(&SocketTunnelConnection::OnReadComplete
,
80 base::Unretained(this)));
81 if (result
== net::ERR_IO_PENDING
)
84 OnReadComplete(result
);
87 void SocketTunnelConnection::OnReadComplete(int result
) {
89 OnDataPacketRead(read_buffer_
->StartOfBuffer(),
90 read_buffer_
->offset() + result
);
96 } // namespace devtools_bridge