summaryrefslogtreecommitdiffstats
path: root/native_client_sdk/src/examples/api/socket/echo_server.h
blob: db35d7a1eac3a05d94a56f2049e11baa58cd353d (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
// Copyright (c) 2013 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.

#ifndef ECHO_SERVER_H_
#define ECHO_SERVER_H_

#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/tcp_socket.h"
#include "ppapi/utility/completion_callback_factory.h"

static const int kBufferSize = 1024;

// Simple "echo" server based on a listening pp::TCPSocket.
// This server handles just one connection at a time and will
// echo back whatever bytes get sent to it.
class EchoServer {
 public:
  EchoServer(pp::Instance* instance, uint16_t port)
    : instance_(instance),
      callback_factory_(this) {
    Start(port);
  }

 protected:
  void Start(uint16_t port);

  // Callback functions
  void OnBindCompletion(int32_t result);
  void OnListenCompletion(int32_t result);
  void OnAcceptCompletion(int32_t result, pp::TCPSocket socket);
  void OnReadCompletion(int32_t result);
  void OnWriteCompletion(int32_t result);

  void TryRead();
  void TryAccept();

  pp::Instance* instance_;
  pp::CompletionCallbackFactory<EchoServer> callback_factory_;
  pp::TCPSocket listening_socket_;
  pp::TCPSocket incoming_socket_;

  char receive_buffer_[kBufferSize];
};

#endif  // ECHO_SERVER_H_