Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

TCPSocket and node.js: socket write() does not work

i'm trying to develop a library which would allow functionality similar to Titanium.API.log, but would be usable from an actual device, which is not connected to the development environment, but only connected to a network (btw, i'm planning to publish the source). node.js is used as a "listening" server component.
problem:when i open tcpsocket on the device with the WRITE_MODE, or READ_WRITE_MODE, and trying to write to the ip/port - nothing happens on the server side, i.e. the write is not being detected on the server at all. everything else works: connection happens and stays open until closed, "write" from the server to the device's socket also works and correctly triggers "read" event on the device.
question:what needs to be done to make tcpsocket "write" actually write to the socket?

— asked January 2nd 2011 by yury bogomo
  • node.js
  • tcpsocket
  • write
2 Comments
  • i got it working (the working code is below).
    the problem was: you need to wait until connection is opened and the socket is valid. in the following code setInterval function keeps being fired until the socket's isValid returns true:

    function tcpClient() 
    { 
        this.socket = null; 
        this.RemoteHost = 'ip address of the node.js server'; 
        this.RemotePort = 'port on that address'; 
        this.timer = -1;
    
        this.newSocket = function() 
        {
            this.socket = Titanium.Network.createTCPSocket(
            {
                hostName: this.RemoteHost, 
                port: parseInt(this.RemotePort, 10),
                mode: Titanium.Network.READ_WRITE_MODE
            });
        };
    
        this.isConnected = function() 
        {
            var ret = false;
    
            if (this.socket != null) 
            {
                ret = this.socket.isValid;
            }
    
            return ret;
        };
    }
    
    function TCPClient_onRead(e) 
    { 
        alert('read: ' + e['data'].text); 
    }
    
    function TCPClient_onReadError(e) 
    { 
        alert('Read error...'); 
    }
    
    function TCPClient_onWriteError(e) 
    { 
        alert('Write error...'); 
    }
    
    function TCPClient_onConnect() 
    { 
        //alert('Waiting for ' + TCPClient.RemoteHost + ':' + TCPClient.RemotePort); 
    
        if (TCPClient.isConnected()) 
        { 
            clearInterval(TCPClient.timer);
    
            TCPClient.socket.addEventListener('read', TCPClient_onRead);
            TCPClient.socket.addEventListener('readError', TCPClient_onReadError);        
            TCPClient.socket.addEventListener('writeError', TCPClient_onWriteError);
    
            //Titanium.API.info('Connected to ' + TCPClient.RemoteHost + ':' + TCPClient.RemotePort);
            //Titanium.API.info('Writing ' + TCPClientBuff + ' to socket...');
    
            TCPClient.socket.write('test');
        }
    }
    
    function Connect() 
    {
        try
        {
            TCPClient = new tcpClient();
    
            if (false)
            {
                TCPClientBuff = 'CIDSetPlusChramCCC' + CID + Level1Delimiter + SoftwareVersion + 'CIDSetMinusChram';
    
                if (TCPClient.isConnected()) 
                { 
                    TCPClient.socket.close(); 
                }
            }
            else
            {
                //TCPClient.RemoteHost = 'localhost';
                TCPClient.RemoteHost = '<node.js ip>';
                TCPClient.RemotePort = 'node.js port';
    
                TCPClient.newSocket();
                TCPClient.socket.connect();
    
                TCPClient.timer = setInterval(TCPClient_onConnect, 2000);
            }
        }
        catch (eee)
        {
            alert('err in tcp: ' + $iwa.str(eee));
        }
    }
    
    — commented January 9th 2011 by yury bogomo
  • would be nice if there would be a class for that. some sort of prototype that fires an event if the socket is ready and connected…

    — commented March 31st 2011 by Tobias O.

2 Answers

  • I got the following echo server in node.js and simple app in titanium working just now.

    node.js echo server

    var net = require('net');
    net.createServer(function(socket) {
      socket.addListener('data', function(data) {
        socket.write(data);
      })
    }).listen(8001);
    

    Titanium App

    <html>
    <head>
    
    <script>
      var tcpsock = null;
      window.onload = function () {
        var myWindow = Titanium.UI.getCurrentWindow();
        myWindow.addEventListener(Titanium.CLOSE, function(event) {
          Titanium.App.exit();
        });
      };
      var connect = function () { 
        tcpsock = Titanium.Network.createTCPSocket(document.getElementById('hostname').value, parseInt(document.getElementById('port').value));
        tcpsock.onRead(function(data) { document.getElementById('received').value += data + "\n"; });
        tcpsock.connect();
      };
      var disconnect = function () {
        tcpsock.close();
      };
      var sendit = function () {
        tcpsock.write(document.getElementById('to_send').value);
        document.getElementById('to_send').value = '';
      };
    </script>
    
    </head>
    <body style="background-color: #1c1c1c; margin: 0;">
      <div style="border-top: 1px solid #404040">
        <div style="color: #fff; padding: 10px;">
          Host: <input type="text" size="25" id="hostname"></input>Port: <input type="text" size="5" id="port"></input><button type="button" onclick="connect();">Connect</button><button type="button" onclick="disconnect();">Disconnect</button><br />
          <textarea rows="03" cols="40" id="to_send"></textarea><button type="button" onclick="sendit();">Send</button><br />
          <textarea rows="10" cols="40" id="received"></textarea><br />
        </div>
      </div>
    </body>
    
    </html>
    

    I hope that helps you!

    — answered January 9th 2011 by Daniel Bartlett
    permalink
    0 Comments
  • it is fully working now.

    i've designed remote debugging system based on tcpsockets available at http://www.cloudebug.com.

    as a part of the code provided with this system you will find a working tcpClient class which you can use in your projects freely.

    here is the link to the post:

    http://developer.appcelerator.com/question/101611/new-debugging-system-for-titanium—cloudebug

    or, you can go to http://www.cloudebug.com, register and get the source code for the tcpClient class.

    good luck!

    yury

    — answered January 17th 2011 by yury bogomo
    permalink
    1 Comment
    • http://www.cloudebug.com

      — commented January 17th 2011 by yury bogomo
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.