summaryrefslogtreecommitdiffstats
path: root/chrome/browser/renderer_host/socket_stream_host.cc
blob: a4b6525d77ec12c266445d23b9145b66a96ce204 (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
// Copyright (c) 2010 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 "chrome/browser/renderer_host/socket_stream_host.h"

#include "base/logging.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/net/socket_stream.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "net/socket_stream/socket_stream_job.h"

static const char* kSocketIdKey = "socketId";

class SocketStreamId : public net::SocketStream::UserData {
 public:
  explicit SocketStreamId(int socket_id) : socket_id_(socket_id) {}
  virtual ~SocketStreamId() {}
  int socket_id() const { return socket_id_; }

 private:
  int socket_id_;
};

SocketStreamHost::SocketStreamHost(
    net::SocketStream::Delegate* delegate,
    int socket_id)
    : delegate_(delegate),
      socket_id_(socket_id) {
  DCHECK_NE(socket_id_, chrome_common_net::kNoSocketId);
  VLOG(1) << "SocketStreamHost: socket_id=" << socket_id_;
}

/* static */
int SocketStreamHost::SocketIdFromSocketStream(net::SocketStream* socket) {
  net::SocketStream::UserData* d = socket->GetUserData(kSocketIdKey);
  if (d) {
    SocketStreamId* socket_stream_id = static_cast<SocketStreamId*>(d);
    return socket_stream_id->socket_id();
  }
  return chrome_common_net::kNoSocketId;
}

SocketStreamHost::~SocketStreamHost() {
  VLOG(1) << "SocketStreamHost destructed socket_id=" << socket_id_;
  socket_->DetachDelegate();
}

void SocketStreamHost::Connect(const GURL& url) {
  VLOG(1) << "SocketStreamHost::Connect url=" << url;
  socket_ = net::SocketStreamJob::CreateSocketStreamJob(url, delegate_);
  URLRequestContextGetter* context_getter = Profile::GetDefaultRequestContext();
  if (context_getter)
      socket_->set_context(context_getter->GetURLRequestContext());
  socket_->SetUserData(kSocketIdKey, new SocketStreamId(socket_id_));
  socket_->Connect();
}

bool SocketStreamHost::SendData(const std::vector<char>& data) {
  VLOG(1) << "SocketStreamHost::SendData";
  return socket_ && socket_->SendData(&data[0], data.size());
}

void SocketStreamHost::Close() {
  VLOG(1) << "SocketStreamHost::Close";
  if (!socket_)
    return;
  socket_->Close();
}