1 module osc.client;
2 
3 import std.socket;
4 
5 import osc.packet;
6 
7 
8 
9 /// An OSC client object. It uses a default send address, but it can also
10 /// send any OSC packet to any given address.
11 ///
12 class OSCClient
13 {
14 	private {
15 		Socket 	_socket;
16 		Address _address;
17 	}
18 
19 
20 
21 	/// Constructs a new OSC client using a socket and an address.
22 	///
23 	this( Socket sock, Address addr )
24 	{
25 		_socket = sock;
26 		_address = addr;
27 	}
28 
29 	/// Constructs a new OSC client using an address and creating an UDP socket
30 	/// for IPv4 addresses.
31 	///
32 	this( Address addr )
33 	{
34 		this( new Socket( AddressFamily.INET, SocketType.DGRAM ), addr );
35 	}
36 
37 	/// Constructs a new OSC client using an IPv4 address and creating an
38 	/// UDP socket for IPv4 addresses.
39 	///
40 	this( string ip, ushort port )
41 	{
42 		this( new InternetAddress( ip, port ) );
43 	}
44 
45 	/// Constructs a new OSC client using a localhost address with the given
46 	/// port, and creating an UDP socket for IPv4 addresses.
47 	///
48 	this( ushort port )
49 	{
50 		this( "localhost", port );
51 	}
52 
53 
54 
55 	/// Sends the given packet to the default address.
56 	///
57 	OSCClient send( OSCPacket p )
58 	{
59 		return sendTo( _address, p );
60 	}
61 
62 	/// Sends the given packet to the given address.
63 	///
64 	OSCClient sendTo( Address addr, OSCPacket p )
65 	{
66 		_socket.sendTo( p.data, addr );
67 		return this;
68 	}
69 
70 }
71 
72 
73 unittest
74 {
75 	import osc.server:OSCServer;
76 	import osc.message:OSCMessage;
77 	import core.thread:Thread;
78 	import std.datetime:dur;
79 
80 	OSCServer server = new OSCServer( );
81 	server.bind( 15_050 );
82 
83 	assert( server.empty );
84 
85 
86 	OSCClient client = new OSCClient( 15_050 );
87 	Thread.sleep( dur!"seconds"( 1 ) );
88 
89 
90 	OSCMessage mesg = new OSCMessage( "/test" );
91 	mesg.add!float( 440 );
92 
93 	client.send( mesg );
94 
95 	while( server.empty )
96 		Thread.sleep( dur!"seconds"( 1 ) );
97 	
98 
99 	OSCMessage received = cast(OSCMessage) server.pop;
100 
101 	assert( received !is null );
102 
103 	assert( mesg.address == received.address );
104 	assert( mesg.types == received.types );
105 	assert( mesg.at!float( 0 ) == received.at!float( 0 ) );
106 	
107 	server.close;
108 }