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

/extension/content/tcpclient.js

https://github.com/sid984/firefox-freenet-plugin
JavaScript | 83 lines | 70 code | 12 blank | 1 comment | 2 complexity | eab4d866fe84a2d0d187436274fe1cac MD5 | raw file
  1. var TcpClient = new Class({
  2. initialize: function(host, port, listener){
  3. this.host = host;
  4. this.port = port;
  5. for(var k in listener)
  6. this[k] = listener[k];
  7. this.data = "";
  8. log("init tcpclient");
  9. },
  10. connect: function(){
  11. try{
  12. log("Connecting to " + this.host + ":" + this.port + " ...");
  13. var socketTransportService = Components.classes["@mozilla.org/network/socket-transport-service;1"]
  14. .getService(Components.interfaces.nsISocketTransportService);
  15. this.socketTransport = socketTransportService.createTransport(["starttls"], 1, this.host, this.port, null);
  16. this.inputStream = this.socketTransport.openInputStream(0, 0, 0);
  17. this.scriptible = Components.classes["@mozilla.org/scriptableinputstream;1"]
  18. .createInstance(Components.interfaces.nsIScriptableInputStream);
  19. this.scriptible.init(this.inputStream);
  20. this.outputStream = this.socketTransport.openOutputStream(0, 0, 0);
  21. var pump = Components.classes["@mozilla.org/network/input-stream-pump;1"]
  22. .createInstance(Components.interfaces.nsIInputStreamPump);
  23. pump.init(this.inputStream, -1, -1, 0, 0, true); //!!!!!!! false ?
  24. pump.asyncRead(this, null);
  25. } catch(e) {
  26. alert(e);
  27. }
  28. },
  29. write: function(data){
  30. try{
  31. this.outputStream.write(data, data.length);
  32. log("Sent [" + data + "]");
  33. } catch(e){
  34. log("Socket write error");
  35. }
  36. },
  37. close: function(){
  38. if(this.connected){
  39. this.inputStream.close();
  40. this.outputStream.close();
  41. this.connected = false;
  42. this.onClose();
  43. }
  44. },
  45. onStartRequest: function(request, context){
  46. log("Start connecting to socket...");
  47. this.connected = true;
  48. this.onConnect();
  49. },
  50. onStopRequest: function(request, context, status){
  51. log("Connection to socket closed");
  52. this.close();
  53. },
  54. onDataAvailable: function(request, context, inputStream, offset, count){
  55. log("Data avaiable ["+count+"] long");
  56. try
  57. {
  58. var reply = this.scriptible.read(count);
  59. //log( "Reading ["+count+"]["+offset+"]["+reply+"]");
  60. this.onData(reply);
  61. this.data += reply;
  62. }
  63. catch( ex )
  64. {
  65. alert("Error on Data Avaialable ["+ex+"]");
  66. }
  67. },
  68. onData: function(){}, // OVERRIDE
  69. onConnect: function(){}, // OVERRIDE
  70. onClose: function(){} // OVERRIDE
  71. });