Search code examples
javascriptcvisual-studiowebsocketwinsock2

Winsock2 c sokcet to a Javascript Websocket server


I'm trying trying to send data from a c file using winsock2 compiled with Visual Studio to a WebSocket server in Javascript. But I didn't succeed in making them communicate on windows. As I'm not a c visual studio and socket expert, I don't understand why the C client does not send any data to my JS WebSocket server.

Here are the two following "code" that I'm using. If you have some tips or a good ideas. Feel free to answer.

C code

#include <winsock2.h>

#include <hmi_api.h>
#include <stdio.h>
#include <io.h>
#include <string.h>
#include <Windows.h>

int main(int argc, char** argv) {

WSADATA wsa;
SOCKET s;
char* message;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
    printf("Failed. Error Code : %d", WSAGetLastError());
    return 1;
}

printf("Initialised.\n");

//Create a socket
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
    printf("Could not create socket : %d", WSAGetLastError());
}

printf("Socket created.\n");


struct sockaddr_in server;

server.sin_family = AF_INET;
server.sin_port = htons(8081);
server.sin_addr.s_addr = inet_addr("127.0.0.1");

//Connect to remote server
if (connect(s, (struct sockaddr*)&server, sizeof(server)) < 0)
{
    puts("connect error");
    return 1;
}

puts("Connected");

message = "Hello";
if (send(s, message, strlen(message), 0) < 0)
{
    puts("Send failed");
    return 1;
}
puts("Data Send\n");

int while_count = 0;

while(while_count < 10){

     char* test_message = "Test";
     send(s,test_message,sizeof(test_message),0);
     while_count++;
}

}

Javscript Code

var webSocketServer = require('ws').Server;
var socket = new webSocketServer({port:8081,host:'127.0.0.1'})
const { table } = require('console');
var fs = require('fs');

console.log("Starting")
socket.on('connection',function(ws){
  console.log("client connected")
   ws.on('message', function(message){
    console.log(JSON.parse(message))
    dataset.table.push(JSON.parse(message))
  })

})

Thank you very much !

R.


Solution

  • I found the problem! This javascript websocket was not adequate to the C socket. Thus, I tried the following Javascript code and it is workings as wanted !

    net = require('net');
    
    net.createServer(function (socket) {
    
        socket.on('data', function (data) {
            console.log(JSON.parse(data));
        });
        socket.on('error', function(e){
            console.log(e);
        });
    
    
    }).listen(5000);
    
    console.log("Chat server running at port 5000\n");