Hey guys, something I was working on for my dissertation. I needed a nice and easy UDP library for the Windows 8 JS libraries. To clear things up, I know you can already use UDP in the Windows 8 libs. This is a simple wrapper to make my life a hell of a lot easier.
For those of you unaware of what typescript is, its a wrapper library for Javascript by Microsoft. Basically it makes life a hell of a lot easier by making your javascript code mode scaleable. All typescript code compiles to pure javascript, and you may use pure javascript in typescript. You can get it here:
http://www.typescriptlang.org/Here is the library itself:
module Connection {
export class UDPSocket {
// The socket
socket: Windows.Networking.Sockets.DatagramSocket = null;
connected: bool = false;
port: string;
constructor(port: string) {
this.port = port;
this.socket = new Windows.Networking.Sockets.DatagramSocket();
}
/* Binds to the port set in the constructor */
bind() {
var This: any = this;
(<any>this.socket).bindServiceNameAsync(this.port).done(function () {
This.connected = true;
}, null);
}
broadcast(message: string) {
// No need to set port because broadcasts are supposed to go to all.
this.send("255.255.255.255", message);
};
send(address: string, message: string) {
// If we are not connected yet, wait until we are.
if (this.connected == false) setTimeout(function () { this.broadcast(address, message); }, 1);
var Host: Windows.Networking.HostName = new Windows.Networking.HostName(address);
this.socket.getOutputStreamAsync(Host, this.port).done(function (stream) {
var writer: Windows.Storage.Streams.DataWriter = new Windows.Storage.Streams.DataWriter(stream);
writer.writeString(message);
writer.storeAsync().done(function () { });
});
};
addMessageListener(func: any) {
(<any>this.socket).addEventListener("messagereceived", function (arg: any) {
var messageLength: number = arg.getDataReader().unconsumedBufferLength;
var message: string = arg.getDataReader().readString(messageLength);
console.log(message);
});
}
};
}
Create a file called connection.ts and paste this into it.
Below is an example of the usage:
/*
Example usage of lib
*/
var UDP: Connection.UDPSocket = new Connection.UDPSocket("22112");
/* Example of dealing with an incoming message */
UDP.addMessageListener(function (message: string, arg: any) {
console.log(message);
});
UDP.bind();
UDP.broadcast("Why hello there!");
If any of you fancy playing with it, give it a go and let me know if you find any bugs / issues or have suggestions.
NOTE: You must add all messagelisteners before you bind the socket, NOT after. Failure to do this will result in an exception.