split into separate client and server for sending/listening
This commit is contained in:
parent
3a2db4f0c8
commit
19b3424971
5 changed files with 62 additions and 62 deletions
|
|
@ -2,79 +2,26 @@ import * as dgram from 'dgram';
|
|||
import { OSCArgument, OSCType, toBuffer, fromBuffer, OSCArgumentType } from 'osc-min';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
export interface OSCClientOptions {
|
||||
/** host to output OSC data to */
|
||||
outHost: string;
|
||||
/** port to output OSC data to */
|
||||
outPort: number;
|
||||
/** Local port for incoming OSC messages */
|
||||
inPort?: number;
|
||||
}
|
||||
|
||||
export interface ReceivedOSCMessage<T extends OSCType> {
|
||||
address: string;
|
||||
type: T;
|
||||
value: OSCArgumentType<T>;
|
||||
}
|
||||
|
||||
// declare types for events
|
||||
export declare interface OSCClient {
|
||||
/**
|
||||
Emitted whenever an OSC message is received on inPort
|
||||
@event
|
||||
*/
|
||||
on(event: 'message', listener: (message: ReceivedOSCMessage<OSCType>) => void): this;
|
||||
|
||||
/**
|
||||
Emitted when OSC client is listening on inPort
|
||||
@event
|
||||
*/
|
||||
on(event: 'listening', listener: () => void): this;
|
||||
}
|
||||
|
||||
/**
|
||||
* OSC Client base class, handles sending and receiving OSC messages
|
||||
|
||||
```
|
||||
const osc = new OSCClient({
|
||||
outHost: "192.168.0.68",
|
||||
outPort: 8000,
|
||||
inPort: 8000
|
||||
})
|
||||
const osc = new OSCClient("192.168.0.44", 8000)
|
||||
```
|
||||
*/
|
||||
export class OSCClient extends EventEmitter {
|
||||
private socket: dgram.Socket;
|
||||
private options: OSCClientOptions;
|
||||
constructor(options: OSCClientOptions) {
|
||||
private host: string;
|
||||
private port: number;
|
||||
constructor(host: string, port: number) {
|
||||
super();
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.socket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
|
||||
this.options = options;
|
||||
|
||||
if (options.inPort) {
|
||||
this.socket.bind(options.inPort);
|
||||
}
|
||||
|
||||
this.socket.on('listening', () => {
|
||||
this.emit('listening');
|
||||
});
|
||||
|
||||
this.socket.on('message', (msg) => {
|
||||
const decoded = fromBuffer(msg);
|
||||
if (decoded.oscType === 'message') {
|
||||
decoded.args.forEach((arg) => {
|
||||
this.emit('message', {
|
||||
address: decoded.address,
|
||||
type: arg.type,
|
||||
value: arg.value,
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private sendPacket(packet: Buffer): void {
|
||||
this.socket.send(packet, 0, packet.length, this.options.outPort, this.options.outHost);
|
||||
this.socket.send(packet, 0, packet.length, this.port, this.host);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue