OpenShot Library | libopenshot-audio 0.2.0
juce_Socket.h
1
2/** @weakgroup juce_core-network
3 * @{
4 */
5/*
6 ==============================================================================
7
8 This file is part of the JUCE library.
9 Copyright (c) 2017 - ROLI Ltd.
10
11 JUCE is an open source library subject to commercial or open-source
12 licensing.
13
14 The code included in this file is provided under the terms of the ISC license
15 http://www.isc.org/downloads/software-support-policy/isc-license. Permission
16 To use, copy, modify, and/or distribute this software for any purpose with or
17 without fee is hereby granted provided that the above copyright notice and
18 this permission notice appear in all copies.
19
20 JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
21 EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
22 DISCLAIMED.
23
24 ==============================================================================
25*/
26
27namespace juce
28{
29
30//==============================================================================
31/**
32 A wrapper for a streaming (TCP) socket.
33
34 This allows low-level use of sockets; for an easier-to-use messaging layer on top of
35 sockets, you could also try the InterprocessConnection class.
36
37 @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
38
39 @tags{Core}
40*/
42{
43public:
44 //==============================================================================
45 /** Creates an uninitialised socket.
46
47 To connect it, use the connect() method, after which you can read() or write()
48 to it.
49
50 To wait for other sockets to connect to this one, the createListener() method
51 enters "listener" mode, and can be used to spawn new sockets for each connection
52 that comes along.
53 */
55
56 /** Destructor. */
58
59 //==============================================================================
60 /** Binds the socket to the specified local port.
61
62 @returns true on success; false may indicate that another socket is already bound
63 on the same port
64 */
65 bool bindToPort (int localPortNumber);
66
67 /** Binds the socket to the specified local port and local address.
68
69 If localAddress is not an empty string then the socket will be bound to localAddress
70 as well. This is useful if you would like to bind your socket to a specific network
71 adapter. Note that localAddress must be an IP address assigned to one of your
72 network address otherwise this function will fail.
73 @returns true on success; false may indicate that another socket is already bound
74 on the same port
75 @see bindToPort(int localPortNumber), IPAddress::getAllAddresses
76 */
77 bool bindToPort (int localPortNumber, const String& localAddress);
78
79 /** Returns the local port number to which this socket is currently bound.
80
81 This is useful if you need to know to which port the OS has actually bound your
82 socket when calling the constructor or bindToPort with zero as the
83 localPortNumber argument. Returns -1 if the function fails.
84 */
85 int getBoundPort() const noexcept;
86
87 /** Tries to connect the socket to hostname:port.
88
89 If timeOutMillisecs is 0, then this method will block until the operating system
90 rejects the connection (which could take a long time).
91
92 @returns true if it succeeds.
93 @see isConnected
94 */
95 bool connect (const String& remoteHostname,
97 int timeOutMillisecs = 3000);
98
99 /** True if the socket is currently connected. */
100 bool isConnected() const noexcept { return connected; }
101
102 /** Closes the connection. */
103 void close();
104
105 /** Returns the name of the currently connected host. */
106 const String& getHostName() const noexcept { return hostName; }
107
108 /** Returns the port number that's currently open. */
109 int getPort() const noexcept { return portNumber; }
110
111 /** True if the socket is connected to this machine rather than over the network. */
112 bool isLocal() const noexcept;
113
114 /** Returns the OS's socket handle that's currently open. */
115 int getRawSocketHandle() const noexcept { return handle; }
116
117 //==============================================================================
118 /** Waits until the socket is ready for reading or writing.
119
120 If readyForReading is true, it will wait until the socket is ready for
121 reading; if false, it will wait until it's ready for writing.
122
123 If the timeout is < 0, it will wait forever, or else will give up after
124 the specified time.
125
126 If the socket is ready on return, this returns 1. If it times-out before
127 the socket becomes ready, it returns 0. If an error occurs, it returns -1.
128 */
129 int waitUntilReady (bool readyForReading, int timeoutMsecs);
130
131 /** Reads bytes from the socket.
132
133 If blockUntilSpecifiedAmountHasArrived is true, the method will block until
134 maxBytesToRead bytes have been read, (or until an error occurs). If this
135 flag is false, the method will return as much data as is currently available
136 without blocking.
137
138 @returns the number of bytes read, or -1 if there was an error.
139 @see waitUntilReady
140 */
141 int read (void* destBuffer, int maxBytesToRead,
143
144 /** Writes bytes to the socket from a buffer.
145
146 Note that this method will block unless you have checked the socket is ready
147 for writing before calling it (see the waitUntilReady() method).
148
149 @returns the number of bytes written, or -1 if there was an error.
150 */
151 int write (const void* sourceBuffer, int numBytesToWrite);
152
153 //==============================================================================
154 /** Puts this socket into "listener" mode.
155
156 When in this mode, your thread can call waitForNextConnection() repeatedly,
157 which will spawn new sockets for each new connection, so that these can
158 be handled in parallel by other threads.
159
160 @param portNumber the port number to listen on
161 @param localHostName the interface address to listen on - pass an empty
162 string to listen on all addresses
163 @returns true if it manages to open the socket successfully.
164
165 @see waitForNextConnection
166 */
167 bool createListener (int portNumber, const String& localHostName = String());
168
169 /** When in "listener" mode, this waits for a connection and spawns it as a new
170 socket.
171
172 The object that gets returned will be owned by the caller.
173
174 This method can only be called after using createListener().
175
176 @see createListener
177 */
178 StreamingSocket* waitForNextConnection() const;
179
180private:
181 //==============================================================================
182 String hostName;
183 std::atomic<int> portNumber { 0 }, handle { -1 };
184 std::atomic<bool> connected { false };
185 bool isListener = false;
186 mutable CriticalSection readLock;
187
188 StreamingSocket (const String& hostname, int portNumber, int handle);
189
190 JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket)
191};
192
193
194//==============================================================================
195/**
196 A wrapper for a datagram (UDP) socket.
197
198 This allows low-level use of sockets; for an easier-to-use messaging layer on top of
199 sockets, you could also try the InterprocessConnection class.
200
201 @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
202
203 @tags{Core}
204*/
206{
207public:
208 //==============================================================================
209 /**
210 Creates a datagram socket.
211
212 You first need to bind this socket to a port with bindToPort if you intend to read
213 from this socket.
214
215 If enableBroadcasting is true, the socket will be allowed to send broadcast messages
216 (may require extra privileges on linux)
217 */
218 DatagramSocket (bool enableBroadcasting = false);
219
220
221 /** Destructor. */
223
224 //==============================================================================
225 /** Binds the socket to the specified local port.
226
227 The localPortNumber is the port on which to bind this socket. If this value is 0,
228 the port number is assigned by the operating system.
229
230 @returns true on success; false may indicate that another socket is already bound
231 on the same port
232 */
233 bool bindToPort (int localPortNumber);
234
235 /** Binds the socket to the specified local port and local address.
236
237 If localAddress is not an empty string then the socket will be bound to localAddress
238 as well. This is useful if you would like to bind your socket to a specific network
239 adapter. Note that localAddress must be an IP address assigned to one of your
240 network address otherwise this function will fail.
241 @returns true on success; false may indicate that another socket is already bound
242 on the same port
243 @see bindToPort(int localPortNumber), IPAddress::getAllAddresses
244 */
245 bool bindToPort (int localPortNumber, const String& localAddress);
246
247 /** Returns the local port number to which this socket is currently bound.
248
249 This is useful if you need to know to which port the OS has actually bound your
250 socket when bindToPort was called with zero.
251
252 Returns -1 if the socket didn't bind to any port yet or an error occurred. */
253 int getBoundPort() const noexcept;
254
255 /** Returns the OS's socket handle that's currently open. */
256 int getRawSocketHandle() const noexcept { return handle; }
257
258 //==============================================================================
259 /** Waits until the socket is ready for reading or writing.
260
261 If readyForReading is true, it will wait until the socket is ready for
262 reading; if false, it will wait until it's ready for writing.
263
264 If the timeout is < 0, it will wait forever, or else will give up after
265 the specified time.
266
267 If the socket is ready on return, this returns 1. If it times-out before
268 the socket becomes ready, it returns 0. If an error occurs, it returns -1.
269 */
270 int waitUntilReady (bool readyForReading, int timeoutMsecs);
271
272 /** Reads bytes from the socket.
273
274 If blockUntilSpecifiedAmountHasArrived is true, the method will block until
275 maxBytesToRead bytes have been read, (or until an error occurs). If this
276 flag is false, the method will return as much data as is currently available
277 without blocking.
278
279 @returns the number of bytes read, or -1 if there was an error.
280 @see waitUntilReady
281 */
282 int read (void* destBuffer, int maxBytesToRead,
284
285 /** Reads bytes from the socket and return the IP address of the sender.
286
287 If blockUntilSpecifiedAmountHasArrived is true, the method will block until
288 maxBytesToRead bytes have been read, (or until an error occurs). If this
289 flag is false, the method will return as much data as is currently available
290 without blocking.
291
292 @returns the number of bytes read, or -1 if there was an error. On a successful
293 result, the senderIPAddress value will be set to the IP of the sender.
294 @see waitUntilReady
295 */
296 int read (void* destBuffer, int maxBytesToRead,
299
300 /** Writes bytes to the socket from a buffer.
301
302 Note that this method will block unless you have checked the socket is ready
303 for writing before calling it (see the waitUntilReady() method).
304
305 @returns the number of bytes written, or -1 if there was an error.
306 */
307 int write (const String& remoteHostname, int remotePortNumber,
308 const void* sourceBuffer, int numBytesToWrite);
309
310 /** Closes the underlying socket object.
311
312 Closes the underlying socket object and aborts any read or write operations.
313 Note that all other methods will return an error after this call. This
314 method is useful if another thread is blocking in a read/write call and you
315 would like to abort the read/write thread. Simply deleting the socket
316 object without calling shutdown may cause a race-condition where the read/write
317 returns just before the socket is deleted and the subsequent read/write would
318 try to read from an invalid pointer. By calling shutdown first, the socket
319 object remains valid but all current and subsequent calls to read/write will
320 return immediately.
321 */
322 void shutdown();
323
324 //==============================================================================
325 /** Join a multicast group.
326 @returns true if it succeeds.
327 */
328 bool joinMulticast (const String& multicastIPAddress);
329
330 /** Leave a multicast group.
331 @returns true if it succeeds.
332 */
333 bool leaveMulticast (const String& multicastIPAddress);
334
335 /** Enables or disables multicast loopback.
336 @returns true if it succeeds.
337 */
338 bool setMulticastLoopbackEnabled (bool enableLoopback);
339
340 //==============================================================================
341 /** Allow other applications to re-use the port.
342
343 Allow any other application currently running to bind to the same port.
344 Do not use this if your socket handles sensitive data as it could be
345 read by any, possibly malicious, third-party apps.
346
347 Returns true on success.
348 */
349 bool setEnablePortReuse (bool enabled);
350
351private:
352 //==============================================================================
353 std::atomic<int> handle { -1 };
354 bool isBound = false;
355 String lastBindAddress, lastServerHost;
356 int lastServerPort = -1;
357 void* lastServerAddress = nullptr;
358 mutable CriticalSection readLock;
359
360 JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket)
361};
362
363} // namespace juce
364
365/** @}*/
Holds a resizable array of primitive or copy-by-value objects.
Definition juce_Array.h:60
A wrapper for a datagram (UDP) socket.
int getRawSocketHandle() const noexcept
Returns the OS's socket handle that's currently open.
A wrapper for a streaming (TCP) socket.
Definition juce_Socket.h:42
int getPort() const noexcept
Returns the port number that's currently open.
const String & getHostName() const noexcept
Returns the name of the currently connected host.
bool isConnected() const noexcept
True if the socket is currently connected.
The JUCE String class!
Definition juce_String.h:43
#define JUCE_API
This macro is added to all JUCE public class declarations.