sync_socket.h revision ddb351dbec246cf1fab5ec20d2d5520909041de1
1// Copyright (c) 2011 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#ifndef BASE_SYNC_SOCKET_H_
6#define BASE_SYNC_SOCKET_H_
7#pragma once
8
9// A socket abstraction used for sending and receiving plain
10// data.  Because they are blocking, they can be used to perform
11// rudimentary cross-process synchronization with low latency.
12
13#include "base/basictypes.h"
14#if defined(OS_WIN)
15#include <windows.h>
16#endif
17#include <sys/types.h>
18
19#include "base/base_api.h"
20
21namespace base {
22
23class BASE_API SyncSocket {
24 public:
25#if defined(OS_WIN)
26  typedef HANDLE Handle;
27#else
28  typedef int Handle;
29#endif
30
31  // Creates a SyncSocket from a Handle.  Used in transport.
32  explicit SyncSocket(Handle handle) : handle_(handle) { }
33  ~SyncSocket() { Close(); }
34
35  // Creates an unnamed pair of connected sockets.
36  // pair is a pointer to an array of two SyncSockets in which connected socket
37  // descriptors are returned.  Returns true on success, false on failure.
38  static bool CreatePair(SyncSocket* pair[2]);
39
40  // Closes the SyncSocket.  Returns true on success, false on failure.
41  bool Close();
42
43  // Sends the message to the remote peer of the SyncSocket.
44  // Note it is not safe to send messages from the same socket handle by
45  // multiple threads simultaneously.
46  // buffer is a pointer to the data to send.
47  // length is the length of the data to send (must be non-zero).
48  // Returns the number of bytes sent, or 0 upon failure.
49  size_t Send(const void* buffer, size_t length);
50
51  // Receives a message from an SyncSocket.
52  // buffer is a pointer to the buffer to receive data.
53  // length is the number of bytes of data to receive (must be non-zero).
54  // Returns the number of bytes received, or 0 upon failure.
55  size_t Receive(void* buffer, size_t length);
56
57  // Returns the number of bytes available. If non-zero, Receive() will not
58  // not block when called. NOTE: Some implementations cannot reliably
59  // determine the number of bytes available so avoid using the returned
60  // size as a promise and simply test against zero.
61  size_t Peek();
62
63  // Extracts the contained handle.  Used for transferring between
64  // processes.
65  Handle handle() const { return handle_; }
66
67 private:
68  Handle handle_;
69
70  DISALLOW_COPY_AND_ASSIGN(SyncSocket);
71};
72
73}  // namespace base
74
75#endif  // BASE_SYNC_SOCKET_H_
76