blob: 7051d94bbc12609eac531cd734755ebf7a4d3dd4 [file] [log] [blame]
Ryan Keanedeb48b32019-06-28 16:24:40 -07001// Copyright 2019 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
4
5#include "platform/api/udp_socket.h"
6
Ryan Keanea4dfaa12019-08-19 10:30:20 -07007#include "platform/api/task_runner.h"
8
Ryan Keanedeb48b32019-06-28 16:24:40 -07009namespace openscreen {
10namespace platform {
11
Ryan Keanea4dfaa12019-08-19 10:30:20 -070012UdpSocket::UdpSocket(TaskRunner* task_runner, Client* client)
13 : client_(client), task_runner_(task_runner) {
14 OSP_CHECK(task_runner_);
Ryan Keanedeb48b32019-06-28 16:24:40 -070015 deletion_callback_ = [](UdpSocket* socket) {};
16}
17
18UdpSocket::~UdpSocket() {
Ryan Keane83050af2019-08-26 08:58:09 -070019 OSP_DCHECK(is_closed_);
Ryan Keanedeb48b32019-06-28 16:24:40 -070020}
21
22void UdpSocket::SetDeletionCallback(std::function<void(UdpSocket*)> callback) {
23 deletion_callback_ = callback;
24}
25
Ryan Keane63fbedd2019-08-19 12:33:41 -070026void UdpSocket::OnError(Error error) {
Ryan Keane83050af2019-08-26 08:58:09 -070027 CloseIfError(error);
28
Ryan Keane63fbedd2019-08-19 12:33:41 -070029 if (!client_) {
30 return;
31 }
32
33 task_runner_->PostTask([e = std::move(error), this]() mutable {
34 this->client_->OnError(this, std::move(e));
35 });
36}
37void UdpSocket::OnSendError(Error error) {
38 if (!client_) {
39 return;
40 }
41
42 task_runner_->PostTask([e = std::move(error), this]() mutable {
43 this->client_->OnSendError(this, std::move(e));
44 });
45}
46void UdpSocket::OnRead(ErrorOr<UdpPacket> read_data) {
47 if (!client_) {
48 return;
49 }
50
51 task_runner_->PostTask([data = std::move(read_data), this]() mutable {
52 this->client_->OnRead(this, std::move(data));
53 });
54}
55
Ryan Keane83050af2019-08-26 08:58:09 -070056void UdpSocket::CloseIfError(const Error& error) {
57 if (error.code() != Error::Code::kNone &&
58 error.code() != Error::Code::kAgain) {
59 CloseIfOpen();
60 }
61}
62
63void UdpSocket::CloseIfOpen() {
64 if (!is_closed_.exchange(true)) {
65 deletion_callback_(this);
66 Close();
67 }
68}
69
Ryan Keanedeb48b32019-06-28 16:24:40 -070070} // namespace platform
71} // namespace openscreen