aboutsummaryrefslogtreecommitdiff
path: root/cast/common/channel/cast_socket_message_port.cc
blob: 8d255e6daeb60967cabf7d4d1415085faeb1470e (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
// Copyright 2019 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 "cast/common/channel/cast_socket_message_port.h"

#include <utility>

#include "cast/common/channel/proto/cast_channel.pb.h"

namespace openscreen {
namespace cast {

CastSocketMessagePort::CastSocketMessagePort() = default;
CastSocketMessagePort::~CastSocketMessagePort() = default;

// NOTE: we assume here that this message port is already the client for
// the passed in socket, so leave the socket's client unchanged. However,
// since sockets should map one to one with receiver sessions, we reset our
// client. The consumer of this message port should call SetClient with the new
// message port client after setting the socket.
void CastSocketMessagePort::SetSocket(WeakPtr<CastSocket> socket) {
  client_ = nullptr;
  socket_ = socket;
}

int CastSocketMessagePort::GetSocketId() {
  return socket_ ? socket_->socket_id() : -1;
}

void CastSocketMessagePort::SetClient(MessagePort::Client* client) {
  client_ = client;
}

void CastSocketMessagePort::PostMessage(const std::string& sender_id,
                                        const std::string& message_namespace,
                                        const std::string& message) {
  ::cast::channel::CastMessage cast_message;
  cast_message.set_source_id(sender_id.data(), sender_id.size());
  cast_message.set_namespace_(message_namespace.data(),
                              message_namespace.size());
  cast_message.set_payload_utf8(message.data(), message.size());

  if (!socket_) {
    client_->OnError(Error::Code::kAlreadyClosed);
    return;
  }
  Error error = socket_->Send(cast_message);
  if (!error.ok()) {
    client_->OnError(error);
  }
}

}  // namespace cast
}  // namespace openscreen