Example of c++ client and node.js server

Viewed 763

I have a problem... I'm trying to connect my client written in c++ to my server written in nodejs but I couldn't do. How can i receive data in the server? With this code I receive the client connection but not the data that it sends. I will appreciate a simple example to send and receive data from a c++ client and nodejs server.

This is my client.cpp

#include <stdio.h> 
#include <sys/socket.h> 
#include <arpa/inet.h> 
#include <unistd.h> 
#include <string.h> 
#define PORT 8080 
   
int main(int argc, char const *argv[]) 
{ 
    int sock = 0, valread; 
    struct sockaddr_in serv_addr; 
    char *hello = "Hello from client"; 
    char buffer[1024] = {0}; 
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) 
    { 
        printf("\n Socket creation error \n"); 
        return -1; 
    } 
   
    serv_addr.sin_family = AF_INET; 
    serv_addr.sin_port = htons(PORT); 
       
    // Convert IPv4 and IPv6 addresses from text to binary form 
    if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)  
    { 
        printf("\nInvalid address/ Address not supported \n"); 
        return -1; 
    } 
   
    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) 
    { 
        printf("\nConnection Failed \n"); 
        return -1; 
    } 
    send(sock , hello , strlen(hello) , 0 ); 
    printf("Hello message sent\n"); 
    //valread = read( sock , buffer, 1024); 
    //printf("%s\n",buffer ); 
    return 0; 
} 

This is my server.js

const server = require('http').createServer();

const io = require('socket.io')(server, {
  path: '/test',
  serveClient: false,
  // below are engine.IO options
  pingInterval: 10000,
  pingTimeout: 5000,
  cookie: false
});

server.on('connection', function (client) {
    console.log("New connection");
  });

server.on('data', function (client) {
    console.log("New data");
});

server.on('close', () => {
    console.log('Subscriber disconnected.');
});

server.listen(8080);
1 Answers

Your client program terminates faster than the server has time to read the data (the socket is closed before the system has time to send the output buffer). Put a 'sleep' (or any other waiting concept) before you exit and look what happens.

p.s. what is the return value of your 'send'?

Related