I am developing a RESTFUL webservice using Django. At some point, we need to click the server object on the connected client without polling the clients. We decided to use django-websocket 0.3.0.
I am writing test cases and trying to connect to the server using nodejs ws client module
The Django My View function is as follows:
from django.http import HttpResponse from django_websocket import accept_websocket, require_websocket from django.views.decorators.csrf import csrf_exempt import json, sys, os, time, datetime @csrf_exempt @accept_websocket def home(request) : if not request.is_websocket(): return HttpResponse('new message') else: for message in request.websocket: message = modify_message(message) request.websocket.send(message) request.websocket.close()
The code of my client side in js looks like this: -
//Normal Get var request = require('request'); request('http://127.0.0.1:8000',function(err,resp,flag){ console.log(resp.body); }); //Opening a websocket var WebSocket = require('ws'); var ws = new WebSocket('ws://127.0.0.1:8000/', {origin: 'http://127.0.0.1:8000'}); ws.on('open', function() { console.log('connected'); ws.send(Date.now().toString(), {mask: true}); }); ws.on('close', function() { console.log('disconnected'); }); ws.on('message', function(data, flags) { console.log('Roundtrip time: ' + (Date.now() - parseInt(data)) + 'ms', flags); setTimeout(function() { ws.send(Date.now().toString(), {mask: true}); }, 500); });
The first option receives the message as a "new message". On the other hand, the second call causes the following error on the client side. On the server side, both commands go through 200OK
events.js:72 throw er; // Unhandled 'error' event ^ Error: unexpected server response (200) at ClientRequest.<anonymous> (../ws/lib/WebSocket.js:603:17) at ClientRequest.g (events.js:175:14) at ClientRequest.EventEmitter.emit (events.js:95:17) at HTTPParser.parserOnIncomingClient [as onIncoming] (http.js:1689:21) at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23) at Socket.socketOnData [as ondata] (http.js:1584:20) at TCP.onread (net.js:525:27)
On the side of the note, if I write request.is_websocket() in both calls, it returns a false value on the server side, it never goes to the other part.
Please help me understand what mistake I am making here.
thanks