How to create Socket.io client in Python to talk to a Sails server

不想你离开。 提交于 2019-12-05 03:40:23

Seems it needs a time from your part to create a sails.io.js compatiblity python wrapper arround the given Socketio library. So i thought sharing the implementations while reading the source code of the client side library.

What sails.io.js library here does that, it converts the .get, .post, .put functions to a request via socketio client that sends the following data.

initialize the socketio client lib with http://localhost:1337

pass data to emit function as a dictionary as described below,

common emit data structure is

emit_data = {

        'method' : 'get', #  get, post, delete depends on requirement

        'headers' : {'header_key': 'header_value'}, # for passing headers

         'data': {'key': 'value'},  # for sending /search/?q=hello, {'q': 'hello'}

         'url': '/hello' # 
}

If you need to convert the last nodejs snippet to this client as

import requests
from socketIO_client import SocketIO

def server_responded(*body):
    print 'response', body

# first we need to get cookie headers for connection
r = requests.get('localhost:1337/__getcookie/')
emit_data = {
  'method' : 'get',
  'url': '/hello',
  'headers': {'Cookie': r.headers['Set-Cookie']},
} 
# update emit_data with extra headers if needed

with SocketIO('localhost', 1337) as socketIO:
    # note: event parameter is request method, here get for GET
    # second parameter is emit_data structured as described above
    socketIO.emit(emit_data['method'], emit_data, server_responded)
    # adjust with your requirements
    socketIO.wait_for_callbacks(seconds=1)

I was never able to address my issue, so I worked around it by creating a relay server to forward messages from Sails.io connection to a socket.io connection and vice-versa.

I created a socket.io server in my Python module using Flask SocketIO, then had my relay connect both the python server (socket.io) and the Sails server (Sails.io).

When message received from SailsJS (Sails.io) then emit/forward it to the python server (socket.io).

In my example, the Sails.io client authenticates to Sails first, but I have NOT implemented authentication for the python server.

// Connects to SailsIO on SailsJS instance
var sailsIO = require('sails.io.js')(require('socket.io-client'));

// Connects to SocketIO server
var socketIO = require('socket.io-client')('https://localhost:7000');

socketIO.on('connect', function() {
    console.log("Connect");
});
socketIO.on('disconnect', function() {
    console.log("Disconnect");
});

var request = require('request');
var inspect = require('eyespect').inspector({
    styles: {
        all: 'magenta'
    }
});

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; // Ignore the certs

/* Options */
sailsIO.sails.url = 'https://192.168.178.20:1337';
sailsIO.sails.rejectUnauthorized = false;
// ...

/* Authenticate */
var authJson = {
    "email": "me@domain.com",
    "password": "mypassword"
};

var options = {
    method: 'put',
    body: authJson,
    json: true,
    url: 'https://192.168.178.20:1337/login',
    headers: {
        'Content-Type': 'application/json'
    }
}

request(options, function(err, res, body) {
    if (err) {
        inspect(err, 'error posting json')
        return
    }
    var headers = res.headers
    var statusCode = res.statusCode
    var cookie = headers['set-cookie'][0].split(';')[0]
    inspect(headers, 'headers');
    inspect(cookie, "Cookie")
    inspect(statusCode, 'statusCode');
    inspect(body, 'body');

    sailsIO.sails.headers = {
        'Cookie': cookie
    };

    /* Connects to SailsJS */
    sailsIO.socket.request({
        method: 'get',
        url: '/path/to',
        data: {
            name: 'john'
        },
        headers: {
            'Cookie': cookie
        }
    }, function(resData, jwres) {
        inspect(jwres, "jwres");
        if (jwres.error) {
            console.log(jwres.statusCode); // => e.g. 403
            return;
        }
        console.log(jwres.statusCode); // => e.g. 200
    });
});

sailsIO.socket.on('connecting', function() {
    console.log('Connecting to server');
});

sailsIO.socket.on('hello', function(data) {
    inspect(JSON.stringify(data), "hello (someone connected)");
});

/**
 * On message from Sails, re-emit to python SocketIO server via socket.io client
 */
sailsIO.socket.on('event', function(data) {
    inspect(JSON.stringify(data), "Data received");
    socketIO.emit('event', data);
});

You need to add __sails_io_sdk_version=0.11.0 in url like this:

var socketIO = require('socket.io-client')('https://localhost:7000/?__sails_io_sdk_version=0.11.0'');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!