PageRenderTime 77ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/chrome/content/UdpClient.js

http://github.com/mkovatsc/Copper
JavaScript | 166 lines | 79 code | 27 blank | 60 comment | 5 complexity | 16263a3fbc582efb5373ef3cfc25c5b4 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. /*******************************************************************************
  2. * Copyright (c) 2012, Institute for Pervasive Computing, ETH Zurich.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * 3. Neither the name of the Institute nor the names of its contributors
  14. * may be used to endorse or promote products derived from this software
  15. * without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS "AS IS" AND
  18. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
  21. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  22. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  23. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  24. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  25. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  26. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  27. * SUCH DAMAGE.
  28. *
  29. * This file is part of the Copper CoAP browser.
  30. ******************************************************************************/
  31. /**
  32. * \file
  33. * Code handling the UDP communication for the CoAP protocol
  34. *
  35. * \author Matthias Kovatsch <kovatsch@inf.ethz.ch>\author
  36. */
  37. /*
  38. * FIXME: inputStream does not separate single datagrams.
  39. * Thus, increased traffic results in merged datagrams, i.e., one or more datagrams are added to the payload of the first one.
  40. * A workaround will probably need native code to provide a datagram handler (transport-service) that pipes them to/from Firefox.
  41. */
  42. CopperChrome.UdpClient = function(myHost, myPort) {
  43. // createTransport requires plain IPv6 address
  44. this.host = myHost.replace(/\[/,'').replace(/\]/,'');
  45. this.port = myPort;
  46. this.transportService = Components.classes["@mozilla.org/network/socket-transport-service;1"].getService(Components.interfaces.nsISocketTransportService);
  47. this.pump = Components.classes["@mozilla.org/network/input-stream-pump;1"].createInstance(Components.interfaces.nsIInputStreamPump);
  48. this.socket = this.transportService.createTransport(["udp"], 1, this.host, this.port, null);
  49. this.outputStream = this.socket.openOutputStream(0,0,0);
  50. this.inputStream = this.socket.openInputStream(0, 0, 0); // 1,0,0 = OPEN_BLOCKING
  51. this.pump.init(this.inputStream, -1, -1, 0, 0, false);
  52. this.pump.asyncRead(this, null);
  53. return this;
  54. };
  55. CopperChrome.UdpClient.prototype = {
  56. host : '',
  57. port : -1,
  58. callback : null,
  59. errorCallback : null,
  60. ended : false,
  61. transportService : null,
  62. pump : null,
  63. socket : null,
  64. outputStream : null,
  65. inputStream : null,
  66. sis : null,
  67. register : function(myCB) {
  68. this.callback = myCB;
  69. },
  70. registerErrorCallback : function(myCB) {
  71. this.errorCallback = myCB;
  72. },
  73. // stream observer functions
  74. onStartRequest : function(request, context) {
  75. ;
  76. },
  77. onStopRequest : function(request, context, status) {
  78. this.outputStream.close();
  79. this.inputStream.close();
  80. if (!this.ended) {
  81. this.errorCallback({getCopperCode:function(){return 'Host/network unreachable';}});
  82. }
  83. },
  84. onDataAvailable : function(request, context, inputStream, offset, count) {
  85. try {
  86. // inputStream is for native code only, hence, using nsIScriptableInputStream
  87. var sis = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
  88. sis.init(inputStream);
  89. // read() cannot handle zero bytes in strings, readBytes() coming in FF4
  90. var byteArray = new Array(count);
  91. for (var i=0; i<count; i++) {
  92. //var ch = sis.readBytes(1); // FF4
  93. var ch = sis.read(1);
  94. byteArray[i] = ch.charCodeAt(0);
  95. // pre FF4 workaround
  96. if (isNaN(byteArray[i])) byteArray[i] = 0x00;
  97. //showByte(byteArray[i])
  98. }
  99. //alert(byteArray);
  100. dump('-receiving UDP datagram-\n');
  101. dump(' Length: '+count+'\n');
  102. dump(' -----------------------\n');
  103. if (this.callback) this.callback(byteArray);
  104. } catch( ex ) {
  105. alert('ERROR: UdpClient.onDataAvailable ['+ex+']');
  106. }
  107. },
  108. // UdpClient functions
  109. shutdown : function() {
  110. // will also trigger onStopRequest()
  111. this.ended = true;
  112. this.outputStream.close();
  113. this.inputStream.close();
  114. this.socket.close(0);
  115. dump('-UDP shut down-----------\n');
  116. },
  117. send : function(datagram) {
  118. try {
  119. this.outputStream.write(datagram, datagram.length);
  120. dump('-sent UDP datagram------\n');
  121. dump(' Length: '+datagram.length+'\n');
  122. dump(' -----------------------\n');
  123. } catch (ex) {
  124. dump('WARNING: UdpClient.send [I/O error]\n');
  125. if (this.errorCallback) {
  126. this.errorCallback({getCopperCode:function(){return 'I/O error';}});
  127. }
  128. }
  129. }
  130. };
  131. /*
  132. function showByte(b) {
  133. var str = '';
  134. for (var j=0; j<8; j++) {
  135. str = ((b & 1<<j)>0 ? '1' : '0') + str;
  136. }
  137. dump('UDP byte ' + b + ': ' + str + '\n');
  138. }
  139. */