从C程序连接到node.js websocket服务器

时间:2017-09-25 07:56:45

标签: c node.js socket.io

我正在尝试从C程序或Chrome扩展程序Smart Websocket Client连接到node.js + socket.io中写入的websocket服务器,但我不能。 我只能从其他nodejs应用程序或js + socket.io。

连接到它

Node.js服务器:

var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

C客户端(我使用github.com/payden/libwsclient):

#include <time.h>
#include <wsclient/wsclient.h>
#include <errno.h>


int onopen(wsclient *c) {
    printf("ad\n");
    fprintf(stderr, "onopen called: %d\n", c->sockfd);
    libwsclient_send(c, "Hello onopen");
    return 0;
}


void initSocketConnection() {
    //char *host = "ws://echo.websocket.org";
    char *host = "ws://127.0.0.1:3000";

    wsclient *client = libwsclient_new(host);

    if(!client) {
        fprintf(stderr, "Unable to initialize new WS client.\n");
        exit(1);
    }
    printf("connecrionnn \n");
    libwsclient_onopen(client, &onopen);

    char *msg = "{\"msg\":\"STATION_READY_FOR_ACTION\", \"appKey\":\"secret-key\"}";
    libwsclient_send(client, msg);
}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我解决了问题,socket端点必须是 “WS://127.0.0.1:3000 / socket.io / EIO = 3及运输= WebSocket的”