0

This is in connection with the question About server-client architecture in express.js

I am currently writing the client part of the program which is supposed to be in express.jsvar

var request = require('request'),
    express = require('express'),
    path    = require('path');

const net = require('net');

var app = express();

// for Express 4.16 above use this instead of
// using body-Parser: app.use(bodyParser.json())
app.use(express.json());


// configuration setting
const PORT1 = 5000;
const port2 = 5001;
const PORT3 = 1337;
const HOST = '127.0.0.1';

app.set('port', (process.env.PORT || PORT1));

var client = new net.Socket();
var id = 0;

// start a tcp connection to connect to server
client.connect(PORT3, HOST, function() {
    console.log('SEND PORT CONNECTED TO: ' + HOST + ':' + PORT3);
});

// using Github for testing web hook
app.post('/getGithub', function(req, res) 
{
    // tester code
    //var data = "20a980dc00b413dc3d0000a3";
    //var data = "e36ace0044ed3d0cc3810000";
    var data = req.body;
    console.log(data);
        
    client.write('Hello, server! Love, Client.' + id + " ");
    client.write(data);
    res.json(data);

});

// http server location
var server = app.listen(app.get('port'), function() {
    var host   = server.address().address
    var portid = server.address().port

    console.log('App listening at http://%s:%s', host, portid)
    console.log("App listening on port " + app.get('port'));
});

// error handler
app.use(function (err, req, res, next) {
    res.status(400).send(err.message)
});

I have some questions here

  1. How do I write a JSON object over to my server application (C++). I know of JSON.stringify(obj) will return string and could be written over?
  2. How do I write my C++ program over the other end? I have written some C++ program but it seem there is some problem while using another express program it seem ok. when I run the C++ program, the client program in express keeps on giving me ECONNECT refused

My C++ program

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <jsoncpp/json/json.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int main()
{
    /* all previous code until
    printf("Reading from client\n"); */

   int listenfd = 0, connfd = 0;    //related with the server
   int MAX_SIZE = 158;
   struct sockaddr_in serv_addr;

   //json_object * jobj;
   char buf[MAX_SIZE], i;

   memset(&buf, '0', sizeof(buf));
   listenfd = socket(AF_INET, SOCK_STREAM, 0);

   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
   serv_addr.sin_port = htons(1337); 

   bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
   printf("binding\n");

   listen(listenfd, 5);
   printf("listening\n");
   connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);

   printf("Reading from client\n");
    ssize_t r;

    for (;;)
    {
        r = read(connfd, buf, MAX_SIZE);

        if (r == -1)
        {
            perror("read");
            return EXIT_FAILURE;
        }
        if (r == 0)
            break;

        printf("READ: %s\n", buf);
    }

    return EXIT_SUCCESS;
}

The error is:

Error: connect ECONNREFUSED 127.0.0.1:1337
    at Object._errnoException (util.js:1022:11)
    at _exceptionWithHostPort (util.js:1044:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)
5
  • 1
    You need to send it as text. And the server should receive it as any other data it receives. But note that the data it receives will not be a null-terminated string. If you want to print the data using the printf format %s you need to add the null-terminator. Commented Dec 16, 2020 at 7:15
  • @Someprogrammerdude : so I should just call it client.write(JSON.stringify(data)); while on the server end(C++ code) i should just read incoming messages as text? Commented Dec 16, 2020 at 7:19
  • Yes that's about it. But remember that null-terminator part in the C++ program. Commented Dec 16, 2020 at 7:20
  • @Someprogrammerdude : Then could I trouble with you why my C++ server program could not work... everytime I start it up and then using the client(express) it will have the error message ECONNECT refused. Commented Dec 16, 2020 at 7:23
  • 1
    Now is the time to do something you should have done immediately: Add error checking in your server program. All the socket functions you call can fail, but you only check read. Commented Dec 16, 2020 at 7:31

1 Answer 1

2

It doesn't matter wich languaje is the server: once you send a Json string, is server independent: You can have a java program, a C++ program, or even, a Apache/PHP program (in this last case, with a HTTP call, using a library, or adding the headers).

First you need your json data

var obj = { name: "John", age: 30, city: "New York" };
var myJSONData = JSON.stringify(obj);

And then, you shoud do a raw socket connection:

var net = require('net');
var HOST = '127.0.0.1';
var PORT = 1337;

// (a) =========
var client = new net.Socket();
client.connect(PORT, HOST, function() {

    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
    client.write(myJSONData );

});
client.destroy();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.