OpenShot Library | OpenShotAudio  0.2.2
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 
27 namespace 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 {
43 public:
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. */
57  ~StreamingSocket();
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 
74  @returns true on success; false may indicate that another socket is already bound
75  on the same port
76  @see bindToPort(int localPortNumber), IPAddress::getAllAddresses
77  */
78  bool bindToPort (int localPortNumber, const String& localAddress);
79 
80  /** Returns the local port number to which this socket is currently bound.
81 
82  This is useful if you need to know to which port the OS has actually bound your
83  socket when calling the constructor or bindToPort with zero as the
84  localPortNumber argument.
85 
86  @returns -1 if the function fails
87  */
88  int getBoundPort() const noexcept;
89 
90  /** Tries to connect the socket to hostname:port.
91 
92  If timeOutMillisecs is 0, then this method will block until the operating system
93  rejects the connection (which could take a long time).
94 
95  @returns true if it succeeds, false if otherwise
96  @see isConnected
97  */
98  bool connect (const String& remoteHostname,
99  int remotePortNumber,
100  int timeOutMillisecs = 3000);
101 
102  /** True if the socket is currently connected. */
103  bool isConnected() const noexcept { return connected; }
104 
105  /** Closes the connection. */
106  void close();
107 
108  /** Returns the name of the currently connected host. */
109  const String& getHostName() const noexcept { return hostName; }
110 
111  /** Returns the port number that's currently open. */
112  int getPort() const noexcept { return portNumber; }
113 
114  /** True if the socket is connected to this machine rather than over the network. */
115  bool isLocal() const noexcept;
116 
117  /** Returns the OS's socket handle that's currently open. */
118  int getRawSocketHandle() const noexcept { return handle; }
119 
120  //==============================================================================
121  /** Waits until the socket is ready for reading or writing.
122 
123  If readyForReading is true, it will wait until the socket is ready for
124  reading; if false, it will wait until it's ready for writing.
125 
126  If the timeout is < 0, it will wait forever, or else will give up after
127  the specified time.
128 
129  @returns 1 if the socket is ready on return, 0 if it times-out before
130  the socket becomes ready, or -1 if an error occurs
131  */
132  int waitUntilReady (bool readyForReading, int timeoutMsecs);
133 
134  /** Reads bytes from the socket.
135 
136  If blockUntilSpecifiedAmountHasArrived is true, the method will block until
137  maxBytesToRead bytes have been read, (or until an error occurs). If this
138  flag is false, the method will return as much data as is currently available
139  without blocking.
140 
141  @returns the number of bytes read, or -1 if there was an error
142  @see waitUntilReady
143  */
144  int read (void* destBuffer, int maxBytesToRead,
145  bool blockUntilSpecifiedAmountHasArrived);
146 
147  /** Writes bytes to the socket from a buffer.
148 
149  Note that this method will block unless you have checked the socket is ready
150  for writing before calling it (see the waitUntilReady() method).
151 
152  @returns the number of bytes written, or -1 if there was an error
153  */
154  int write (const void* sourceBuffer, int numBytesToWrite);
155 
156  //==============================================================================
157  /** Puts this socket into "listener" mode.
158 
159  When in this mode, your thread can call waitForNextConnection() repeatedly,
160  which will spawn new sockets for each new connection, so that these can
161  be handled in parallel by other threads.
162 
163  @param portNumber the port number to listen on
164  @param localHostName the interface address to listen on - pass an empty
165  string to listen on all addresses
166 
167  @returns true if it manages to open the socket successfully
168  @see waitForNextConnection
169  */
170  bool createListener (int portNumber, const String& localHostName = String());
171 
172  /** When in "listener" mode, this waits for a connection and spawns it as a new
173  socket.
174 
175  The object that gets returned will be owned by the caller.
176 
177  This method can only be called after using createListener().
178 
179  @see createListener
180  */
181  StreamingSocket* waitForNextConnection() const;
182 
183 private:
184  //==============================================================================
185  String hostName;
186  std::atomic<int> portNumber { 0 }, handle { -1 };
187  std::atomic<bool> connected { false }, isListener { false };
188  mutable CriticalSection readLock;
189 
190  StreamingSocket (const String& hostname, int portNumber, int handle);
191 
192  JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket)
193 };
194 
195 
196 //==============================================================================
197 /**
198  A wrapper for a datagram (UDP) socket.
199 
200  This allows low-level use of sockets; for an easier-to-use messaging layer on top of
201  sockets, you could also try the InterprocessConnection class.
202 
203  @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
204 
205  @tags{Core}
206 */
208 {
209 public:
210  //==============================================================================
211  /** Creates a datagram socket.
212 
213  You first need to bind this socket to a port with bindToPort if you intend to read
214  from this socket.
215 
216  If enableBroadcasting is true, the socket will be allowed to send broadcast messages
217  (may require extra privileges on linux)
218  */
219  DatagramSocket (bool enableBroadcasting = false);
220 
221 
222  /** Destructor. */
223  ~DatagramSocket();
224 
225  //==============================================================================
226  /** Binds the socket to the specified local port.
227 
228  The localPortNumber is the port on which to bind this socket. If this value is 0,
229  the port number is assigned by the operating system.
230 
231  @returns true on success; false may indicate that another socket is already bound
232  on the same port
233  */
234  bool bindToPort (int localPortNumber);
235 
236  /** Binds the socket to the specified local port and local address.
237 
238  If localAddress is not an empty string then the socket will be bound to localAddress
239  as well. This is useful if you would like to bind your socket to a specific network
240  adapter. Note that localAddress must be an IP address assigned to one of your
241  network address otherwise this function will fail.
242 
243  @returns true on success; false may indicate that another socket is already bound
244  on the same port
245  @see bindToPort(int localPortNumber), IPAddress::getAllAddresses
246  */
247  bool bindToPort (int localPortNumber, const String& localAddress);
248 
249  /** Returns the local port number to which this socket is currently bound.
250 
251  This is useful if you need to know to which port the OS has actually bound your
252  socket when bindToPort was called with zero.
253 
254  @returns -1 if the socket didn't bind to any port yet or an error occurred
255  */
256  int getBoundPort() const noexcept;
257 
258  /** Returns the OS's socket handle that's currently open. */
259  int getRawSocketHandle() const noexcept { return handle; }
260 
261  //==============================================================================
262  /** Waits until the socket is ready for reading or writing.
263 
264  If readyForReading is true, it will wait until the socket is ready for
265  reading; if false, it will wait until it's ready for writing.
266 
267  If the timeout is < 0, it will wait forever, or else will give up after
268  the specified time.
269 
270  @returns 1 if the socket is ready on return, 0 if it times-out before the
271  socket becomes ready, or -1 if an error occurs
272  */
273  int waitUntilReady (bool readyForReading, int timeoutMsecs);
274 
275  /** Reads bytes from the socket.
276 
277  If blockUntilSpecifiedAmountHasArrived is true, the method will block until
278  maxBytesToRead bytes have been read, (or until an error occurs). If this
279  flag is false, the method will return as much data as is currently available
280  without blocking.
281 
282  @returns the number of bytes read, or -1 if there was an error
283  @see waitUntilReady
284  */
285  int read (void* destBuffer, int maxBytesToRead,
286  bool blockUntilSpecifiedAmountHasArrived);
287 
288  /** Reads bytes from the socket and return the IP address of the sender.
289 
290  If blockUntilSpecifiedAmountHasArrived is true, the method will block until
291  maxBytesToRead bytes have been read, (or until an error occurs). If this
292  flag is false, the method will return as much data as is currently available
293  without blocking.
294 
295  @returns the number of bytes read, or -1 if there was an error. On a successful
296  result, the senderIPAddress value will be set to the IP of the sender
297  @see waitUntilReady
298  */
299  int read (void* destBuffer, int maxBytesToRead,
300  bool blockUntilSpecifiedAmountHasArrived,
301  String& senderIPAddress, int& senderPortNumber);
302 
303  /** Writes bytes to the socket from a buffer.
304 
305  Note that this method will block unless you have checked the socket is ready
306  for writing before calling it (see the waitUntilReady() method).
307 
308  @returns the number of bytes written, or -1 if there was an error
309  */
310  int write (const String& remoteHostname, int remotePortNumber,
311  const void* sourceBuffer, int numBytesToWrite);
312 
313  /** Closes the underlying socket object.
314 
315  Closes the underlying socket object and aborts any read or write operations.
316  Note that all other methods will return an error after this call and the object
317  cannot be re-used.
318 
319  This method is useful if another thread is blocking in a read/write call and you
320  would like to abort the read/write thread. Simply deleting the socket
321  object without calling shutdown may cause a race-condition where the read/write
322  returns just before the socket is deleted and the subsequent read/write would
323  try to read from an invalid pointer. By calling shutdown first, the socket
324  object remains valid but all current and subsequent calls to read/write will
325  return immediately.
326  */
327  void shutdown();
328 
329  //==============================================================================
330  /** Join a multicast group.
331 
332  @returns true if it succeeds
333  */
334  bool joinMulticast (const String& multicastIPAddress);
335 
336  /** Leave a multicast group.
337 
338  @returns true if it succeeds
339  */
340  bool leaveMulticast (const String& multicastIPAddress);
341 
342  /** Enables or disables multicast loopback.
343 
344  @returns true if it succeeds
345  */
346  bool setMulticastLoopbackEnabled (bool enableLoopback);
347 
348  //==============================================================================
349  /** Allow other applications to re-use the port.
350 
351  Allow any other application currently running to bind to the same port.
352  Do not use this if your socket handles sensitive data as it could be
353  read by any, possibly malicious, third-party apps.
354 
355  @returns true on success
356  */
357  bool setEnablePortReuse (bool enabled);
358 
359 private:
360  //==============================================================================
361  std::atomic<int> handle { -1 };
362  bool isBound = false;
363  String lastBindAddress, lastServerHost;
364  int lastServerPort = -1;
365  void* lastServerAddress = nullptr;
366  mutable CriticalSection readLock;
367 
368  JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket)
369 };
370 
371 } // namespace juce
372 
373 /** @}*/
A wrapper for a datagram (UDP) socket.
Definition: juce_Socket.h:208
int getRawSocketHandle() const noexcept
Returns the OS's socket handle that's currently open.
Definition: juce_Socket.h:259
A wrapper for a streaming (TCP) socket.
Definition: juce_Socket.h:42
const String & getHostName() const noexcept
Returns the name of the currently connected host.
Definition: juce_Socket.h:109
int getPort() const noexcept
Returns the port number that's currently open.
Definition: juce_Socket.h:112
bool isConnected() const noexcept
True if the socket is currently connected.
Definition: juce_Socket.h:103
The JUCE String class!
Definition: juce_String.h:43
#define JUCE_API
This macro is added to all JUCE public class declarations.