简体   繁体   中英

Receive and send msgs from C client to nodejs server

I have made a TCP client in C, and Im looking to make the server side in nodejs for simplicity and for easy integration into a existing app...

Well in my C code I receive and send msgs in the next way:

numBytes = send( sock, &timeStamp, sizeof( timeStamp ), 0 );
if( numBytes < 0 )
    DieWithSystemMessage( "send( ) failed" );

After reading a little about the "net" and "socket.io" packages for nodejs I haven't found the way to make it work... I apologize if this is somethog simple but it is my first time working with nodejs. If you have some blog or github link that have made something similar I will be glad to take a look, Thanks!!!

You need to use the net module, so a simple TCP listener would look something like:

const
   port = 1234,
   net = require('net');
server = net.createServer(function(connection) {
            connection.write("Welcome to my server"); });
server.listen(port, function() { 
            console.log("Listening..."); });

See Node.js net API for further details

Basically, node works with callbacks due to its asynchronous nature, so if you want to register a callback for a 'message' event on the socket, like that:

server.on('data', function(data) { 
    console.log('Received data');
    /* Do manipulations on the inbound data */
});

So there you define a callback to be executed on a 'data' event, so whenever you receive data on the socket, the anonymus function defined in the on() call will be executed.

Node.JS is very usable for such an application (I started the exact same project a month ago and I didn't have any regrets that I chose Node.JS at all). Here an example code of a Node.JS server:

const port = 46500;
var net = require('net');
var server = net.createServer(function(connection) {
    console.log('client connected');

    connection.on('close', function (){
        console.log('client disconnected');
     });

    connection.on('data', function (data) {
        data = data.toString();
        console.log('client sended the folowing string:'+data);
        connection.write("Response");
        console.log('Sended responst to client');
        connection.end();
        console.log('Disconnected the client.');
   });

});


server.listen(port, function () {
    console.log('server is listening');
}); 

I saw a comment of you in another post where I can't response (due to less than 50 reputation) but you can hard code the ip address of the Node.JS server inside of your c code (but make sure you have a backup option for when the ip of the server changes) or you can implement a DNS client inside of the c application if the server has a domain name.

您可以使用argv传递ip,也可以使用像Hxd这样的十六进制编辑器进行修改。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM