簡體   English   中英

從C客戶端接收和發送msgs到nodejs服務器

[英]Receive and send msgs from C client to nodejs server

我在C中創建了一個TCP客戶端,我希望在nodejs中創建服務器端以簡化並輕松集成到現有應用程序中...

在我的C代碼中,我接收並以下一種方式發送消息:

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

在閱讀了一些關於nodejs的“net”和“socket.io”軟件包之后,我還沒有找到讓它工作的方法...我很抱歉,如果這是簡單的東西,但這是我第一次使用nodejs。 如果你有一些類似的博客或github鏈接我會很高興看看,謝謝!

您需要使用net模塊,因此簡單的TCP偵聽器看起來像:

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

有關更多詳細信息,請參閱Node.js net API

基本上,節點由於其異步性質而使用回調,因此如果要在套接字上注冊“消息”事件的回調,則:

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

因此,您定義了一個要在'data'事件上執行的回調,因此每當您在套接字上接收數據時,on()調用中定義的anonymus函數將被執行。

Node.JS非常適用於這樣的應用程序(我在一個月前開始完全相同的項目,我沒有任何遺憾,我選擇了Node.JS)。 這是Node.JS服務器的示例代碼:

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');
}); 

我在另一篇文章中看到了你的評論,我無法回復(由於聲譽不到50)但你可以在你的c代碼中硬編碼Node.JS服務器的ip地址(但要確保你有備份服務器的IP更改時的選項)或者如果服務器具有域名,您可以在c應用程序內部實現DNS客戶端。

您可以使用argv傳遞ip,也可以使用像Hxd這樣的十六進制編輯器進行修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM