Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function()
- {
- var BUF_SIZE = 10240;
- window.netwerk.JavaUDP = Class(netwerk.Net, {
- init: function(location, port)
- {
- this.Super.init.call(this, location);
- this.socketChannel = java.nio.channels.DatagramChannel.open();
- this.socketChannel.configureBlocking(false);
- this.socketChannel.socket().bind(null); // If the address is null, then the system will pick up an ephemeral port and a valid local address to bind the socket.
- // Note: does not work on localhost
- // And requires your reverse dns to match your domain name
- // (or use an IP to visit the web application)
- this.socketChannel.connect(new java.net.InetSocketAddress(location, port));
- this.readByteBuffer = java.nio.ByteBuffer.allocate(BUF_SIZE);
- this.readByteBuffer.clear();
- this.readBuffer = '';
- this.writeByteBuffer = java.nio.ByteBuffer.allocate(BUF_SIZE);
- this.writeByteBuffer.clear();
- setTimeout(this._readTimer.bind(this), 1);
- return this;
- },
- send: function(json)
- {
- var buf, message, messageLength, a, len;
- message = new java.lang.String(JSON.stringify([json]) + "\n").getBytes('UTF-8');
- messageLength = message.length;
- for (a = 0; a < messageLength; a += BUF_SIZE)
- {
- this.writeByteBuffer.clear();
- if (a + BUF_SIZE >= messageLength)
- {
- len = messageLength - a;
- }
- else
- {
- len = BUF_SIZE;
- }
- this.writeByteBuffer.put(message, a, len);
- this.writeByteBuffer.rewind();
- this.writeByteBuffer.limit(len);
- this.socketChannel.write(this.writeByteBuffer);
- }
- },
- readyToSend: function()
- {
- return !!this.socketChannel.isConnected();
- },
- done: function()
- {
- this._done = true;
- this.socketChannel.close();
- this.socketChannel = null;
- this.readByteBuffer = null;
- this.writeByteBuffer = null;
- },
- _readTimer: function()
- {
- var read, lines, a, json, b;
- if (this._done) return;
- try
- {
- if (!this.socketChannel.isConnected()) return;
- while(true)
- {
- this.readByteBuffer.clear();
- read = this.socketChannel.read(this.readByteBuffer);
- if (read == 0) return;
- if (read < 0)
- {
- this.done();
- return;
- }
- this.readBuffer += new java.lang.String(this.readByteBuffer.array(), 0, read, 'UTF-8') + ''; // impliciet java string naar javascript string
- lines = this.readBuffer.split('\n');
- try
- {
- for (a = 0; a < lines.length - 1; ++a)
- {
- if (!lines[a]) continue; // lege regel
- try
- {
- json = JSON.parse(lines[a]);
- }
- catch(err)
- {
- if (window.console)
- {
- console.log('Unable to parse message from server as json', err);
- }
- continue;
- }
- for (b = 0; b < json.length; b++)
- {
- if (json[b] != null)
- {
- this.onmessage(json[b]);
- }
- }
- }
- }
- finally
- {
- this.readBuffer = lines[lines.length-1];
- }
- }
- }
- finally
- {
- setTimeout(this._readTimer.bind(this), 1);
- }
- }
- });
- window.netwerk.JavaUDP.isSupported = function()
- {
- return !!window.java;
- };
- })();
Add Comment
Please, Sign In to add comment