Ryan Pergent
Ryan Pergent

Reputation: 5366

Connect to a remote socket.io server from Django server

I am trying to build a real-time Django application. Because of the way my hosting service works, I am unable to start a Websocket server in parallel of my Django server.

I managed to have user-to-user interactions by creating an express server on a separate NodeJS website with socket.io, and having clients on the Django server also connect to the remote socket.io server.

However, I'dlike to have my Django server directly send events to users. To do this, I would like to create a connection between the Django server and the NodeJS server. Something like that in python:

socket = io("http://socket.io.server")
socket.emit('eventForUsers')

Is there anyway for me to achieve this?

The only information I found seemed to require me to run a parallel server from my Django app, which I can't do because my host doesn't allow me to run long-term processes.

Upvotes: 0

Views: 1697

Answers (1)

EMX
EMX

Reputation: 6219

It really depends what is the most simple solution for you, and what are your requirements. (If you want realtime bidirectional messaging then I suggest to use the socket.io-client instead of the POST example)


POST (GET,PUT,...)

You can (for example) use POST requests from your Django to Node

Django: python example (there are other ways to perform a POST to Node from Django)

reqParams = {"action":"doThis","data":"put the pizza in the oven"}    
import requests
requests.post('http://ip:port/route', params = reqParams)

Node example : Listens for post at /route (express) and prints the params of the Django request

var express = require('express');
var app = express();

app.post('/route', function (req, res) {
  console.log(req.query); res.end();
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

Then you can use the data in req.params to perform action like broadcasting something to the socket.io clients (or a specific client)

This can also be done the other way around, performing requests to send data from Node to Django using POST (GET,...)


Socket.io-client in Django

Another (easier) solution is to include the socket.io-client in your Django webapp so it connects to your Node socket.io server as a client when the webapp is opened by browsers.

(using javascript in django)

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io('http://ip:port');
  socket.on('connect', function(){alert("Hello World!");});
  socket.on('event', function(data){});
  socket.on('disconnect', function(){});
</script>

More Resources : 1. JavaScript (Django Docs) 2. Including the static files in your template

Upvotes: 2

Related Questions