Saturday, 20 May 2017

Can't create socket server from http module

I wanna create socket server like a Socket.io because socket.io can't work with Corona SDK. So I need custom socket server. I create socket server with using net module and it is work good. But I need using http module because I write REST API. I try create sample socket server from http module but have errors.

var net = require('net');
var HOST = 'localhost';
var PORT = 9999;

var server = require('http').createServer(function(request, response) {
    response.end('Hello from server');
});

server.on('connection', function(socket) {
    socket.on('data', function(data) {
        data = data.toString('utf-8');

        console.log(data);

        socket.write('Hello from server');
    });

    socket.on('error', function(error) {
        console.log(error);
    });
});

server.listen(PORT, HOST);

var client = new net.Socket();
client.connect(PORT, HOST, function() {
    console.log('CONNECTED TO: ' + HOST + ':' + PORT);

    client.write('I am Chuck Norris!');
});

client.on('data', function(data) {
    console.log('DATA: ' + data);

    client.destroy();
});

client.on('close', function() {
    console.log('Connection closed');
});

If I run this script I got error:

CONNECTED TO: localhost:9999
I am Chuck Norris!
Error: This socket is closed
    at Socket._writeGeneric (net.js:692:19)
    at Socket._write (net.js:743:8)
    at doWrite (_stream_writable.js:329:12)
    at writeOrBuffer (_stream_writable.js:315:5)
    at Socket.Writable.write (_stream_writable.js:241:11)
    at Socket.write (net.js:670:40)
    at Socket.<anonymous> (/var/work/projects/edorium/Server/test/test.js:49:16)
    at emitOne (events.js:101:20)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
{ Error: Parse Error
    at socketOnData (_http_server.js:411:20)
    at emitOne (events.js:101:20)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at Socket.Readable.push (_stream_readable.js:136:10)
    at TCP.onread (net.js:560:20) bytesParsed: 0, code: 'HPE_INVALID_METHOD' }
Connection closed

Why this happed and how fix this?



via Metal Evolution Studio

No comments:

Post a Comment