Audacity 3.2.0
IPCClient.cpp
Go to the documentation of this file.
1/**********************************************************************
2
3 Audacity: A Digital Audio Editor
4
5 @file IPCClient.cpp
6
7 @author Vitaly Sverchinsky
8
9 Part of lib-ipc library
10
11**********************************************************************/
12
13#include "IPCClient.h"
14#include "IPCChannel.h"
15
16#include <cstdint>
17#include <thread>
18#include <stdexcept>
19
20#include "internal/ipc-types.h"
23
24class IPCClient::Impl final
25{
26 std::unique_ptr<BufferedIPCChannel> mChannel;
27public:
28
29 Impl(int port, IPCChannelStatusCallback& callback)
30 {
31 auto fd = socket_guard { socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) };
32 if(!fd)
33 throw std::runtime_error("cannot create socket");
34
35#if defined(__unix__) || defined(__APPLE__)
36 auto fdFlags = fcntl(*fd, F_GETFD, 0);
37 if(fdFlags != -1)
38 fcntl(*fd, F_SETFD, fdFlags | FD_CLOEXEC);
39#endif
40
41 sockaddr_in addrin {};
42 addrin.sin_family = AF_INET;
43 addrin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
44 addrin.sin_port = htons(static_cast<uint16_t>(port));
45
46 if(connect(*fd, reinterpret_cast<const sockaddr*>(&addrin), sizeof(addrin)) == SOCKET_ERROR)
47 {
48 callback.OnConnectionError();
49 return;
50 }
51
52 mChannel = std::make_unique<BufferedIPCChannel>();
53 mChannel->StartConversation(fd.release(), callback);
54 }
55};
56
58{
59#ifdef _WIN32
60 WSADATA wsaData;
61 auto result = WSAStartup(MAKEWORD(2, 2), &wsaData);
62 if (result != NO_ERROR)
63 throw std::runtime_error("WSAStartup failed");
64#endif
65 mImpl = std::make_unique<Impl>(port, callback);
66}
67
68IPCClient::~IPCClient() = default;
69
Interface for listening connection status changes.
Definition: IPCChannel.h:37
virtual void OnConnectionError() noexcept=0
Called when connection attempt fails.
std::unique_ptr< BufferedIPCChannel > mChannel
Definition: IPCClient.cpp:26
Impl(int port, IPCChannelStatusCallback &callback)
Definition: IPCClient.cpp:29
std::unique_ptr< Impl > mImpl
Definition: IPCClient.h:25
IPCClient(int port, IPCChannelStatusCallback &callback)
Attempts to connect to a server, may fail with exception or with call to IPCChannelStatusCallback::On...
Definition: IPCClient.cpp:57
~IPCClient()
Closes connection if any.
RAII-style socket wrapper. Since socket is closed on wrapper destruction, initializing multiple guard...
Definition: socket_guard.h:24
#define SOCKET_ERROR
Definition: ipc-types.h:29