node.js domain socket disconnect automatically

91 views Asked by At

My Node.js server is connected to a unix socket developed by C. In each HTTP request, parameter will send to the C program and receive response and send by to client.

But after the first request, the socket is disconnected automatically. What is the reason of disconnection and is there any way to prevent it?

domain_socket.C

include statement..
int main(){
    /* delete the socket file */
    unlink("/tmp/server_socket");

    /* create a socket */
    int server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0);

    struct sockaddr_un server_addr;
    server_addr.sun_family = AF_UNIX;
    strcpy(server_addr.sun_path, "/tmp/server_socket");

    /* bind with the local file */
    bind(server_sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));

    /* listen */
    listen(server_sockfd, 5);

    char data[100];
    char res[100];
    int client_sockfd;
    struct sockaddr_un client_addr;
    socklen_t len = sizeof(client_addr);
    while (1) {
        printf("server waiting:\n");

        /* accept a connection */
        client_sockfd = accept(server_sockfd, (struct sockaddr*)&client_addr, &len);

        /* dummy data processing */
        read(client_sockfd, data, 100);
        printf("Received data: \"%s\"\n", data);
        sprintf(res, "path: %s", data);
        printf("send \"%s\" to client.\n", res);

        write(client_sockfd, res, strlen(res));

        /* close the socket */
        close(client_sockfd);
    }

    return 0;
}

app.js

/* require statement */
var app = express();
var client = net.createConnection("/tmp/server_socket");
client.on('connect', function() {
    console.log('Connected to socket');
});

client.on('end', function() {
    console.log('disconnected');
    client = net.createConnection("/tmp/server_socket");
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

var router = express.Router();

router.get('/query', function(req, res, next) {
    client.write("/home/user/queries/108100.png");
    client.on('data', function(data) {
        res.send(data.toString());
    });
});

app.use('/', router);

module.exports = app;
0

There are 0 answers