Search code examples
node.jsactionscript-3

Connect to AS3 socket server with NODEJS


I'm trying to connect to a socket server which the client is using new Socket() AS3 Class to connect. I'm trying to do something like the AS3 Socket class in nodeJS, how can I do that?

Is there any ready-made library?


Solution

  • This is simplified version of Node.js socket server communicating with flash from one of my projects

    var net = require('net');
    
    var json = "";
    
    var server = net.createServer(function(socket) {
            socket.on('data', function(data) {
                 try {
                        json = JSON.parse(data);
                    } catch (e) {
                        json += data;
    
                        try {
                            json = JSON.parse(json);
                            // Now it's fine.
                        } catch (e) {
                            // Wait for more.
                            return;
                        }
                    }
                //here do something with received JSON
                //then clear it for next message
                json = '';
    
            });
        });
    });
    
    
    server.listen(8888);
    

    In this example over socket was send text JSON but you can use any binary format you want, just write parser. Hope it helps. Sorry didn't see that. But you tried to use google? There are alot of examples, just copy one of them

    var net = require('net');
    
    var client = new net.Socket();
    client.connect(1337, '127.0.0.1', function() {
        console.log('Connected');
        client.write('Hello, server! Love, Client.');
    });
    
    client.on('data', function(data) {
        console.log('Received: ' + data);
        client.destroy(); // kill client after server's response
    });
    
    client.on('close', function() {
        console.log('Connection closed');
    });