django-channels parse json/data sent via sockets - django-channels

I have this javascript code that send data to channels
// Note that the path doesn't matter for routing; any WebSocket
// connection gets bumped over to WebSocket consumers
socket = new WebSocket("ws://" + window.location.host + "/chat/");
socket.onmessage = function(e) {
alert(e.data);
}
socket.onopen = function() {
socket.send({"test":"data"});
}
// Call onopen directly if socket is already open
if (socket.readyState == WebSocket.OPEN) socket.onopen();
I'm curios how from message I can get the json {"test":"data"}
here's the view
# Connected to websocket.connect
#channel_session
def ws_connect(message, key):
# Accept connection
message.reply_channel.send({"accept": True})

You implemented the connection callback, but did not implement what should happen when a message arrives the server endpoint. Add add message receive function:
def on_receive(message):
print('test received: {}'.format(message.content['test']))
Register the function in routing.py:
channel_routing = [
route("websocket.connect", ws_connect),
route("websocket.receive", on_receive),
]
The JSON message you send will be stored in message.content which is basically just a python dict.

Related

Why Twitter is not making a get request to my server while registering webhook using endpoint?

I'm using twitter account activity api for registering a webhook using autohook wrapper library.
As per the docs the post requests to endpoint (https://api.twitter.com/1.1/account_activity/all/:env_name/webhooks.json) should trigger a get request from my server. that will return a crc based on a crc token and my consumer key.
While im getting code 215 and unable to connect during crc request error message again and again.
Im not sure why get request is not exceuting. here is my server and client code.
server.py
#app.route("/webhook/twitter", methods=["GET", "POST"])
def callback() -> json:
if flask.request.method == "GET" or flask.request.method == "PUT":
print(flask.request.args.get("crc_token"))
hash_digest = hmac.digest(
key=os.environ["consumer_secret"].encode("utf-8"),
msg=flask.request.args.get("crc_token").encode("utf-8"),
digest=hashlib.sha256,
)
return {
"response_token": "sha256="
+ base64.b64encode(hash_digest).decode("ascii")
}
elif flask.request.method == "POST":
data = flask.request.get_json()
logging.info(data)
return {"code": 200}
# Once the code running on the server.
# You can register and subscribe to events from your local machine.
#app.route("/",methods=["GET"])
def callbackget():
return "in GEt"
if __name__ == "__main__":
app.run(debug=True, port=443,ssl_context=context)
client side autohook wrapper:
const { Autohook } = require('twitter-autohook');
(async Æ› => {
const webhook = new Autohook(
{
token:"1218220064610099203-8CnN6G3edmIRGdDpLcR7Bao88mMCUg",
token_secret:"JEavuf3PZmSsXWhmSdtNarFPNBp6BsZzMrLpkEMASkJX5",
consumer_key:"6n7U6KDXxouXDcsLMxdiSKwZ9",
consumer_secret:"o2aKE9TivbTwchJXXZ4XaTyAwtCgtoRO35a9PgdaqMLUBRfv49",
env:"enc"
}
);
// Removes existing webhooks
await webhook.removeWebhooks();
// Listens to incoming activity
webhook.on('event', event => console.log('Something happened:', event));
// Starts a server and adds a new webhook
await webhook.start("https://127.0.0.1:443/webhook/twitter");
// Subscribes to a user's activity
await webhook.subscribe({oauth_token, oauth_token_secret});
})();

Socket.io client not working properly

I have created chat application using following
Rails
Rabbitmq
nodejs ( with amqplib/callback_api and socket.io )
I have following code in server side
var amqp = require('amqplib/callback_api');
var amqpConn = null;
var app = require('http').createServer()
var io = require('socket.io')(app);
var fs = require('fs');
io.on('connection', function (socket) {
socket.emit('news/1', msg.content.toString());
// socket.disconnect()
});
client side
<%= javascript_include_tag "http://localhost:53597/socket.io/socket.io.js" %>
<script>
var socket = io('http://localhost:53597', {reconnect: true});
socket.on('connect', function () {
console.log('connected');
socket.on('news/1', function (msg) {
console.log('inside coming');
console.log(msg);
});
});
</script>
When I send message, message successfully pushed to queue and messages emitted to socket. The problem is I can get messages when only refresh page and messages are not deleted.
I can't understand what was wrong here ?
Eventually I fixed my issue, the problem is I have placed emit function inside connection event, so that I can get data when only connection established​, connection is established when page load that is the reason I get data when only page load.
I have the following code for emit data
io.sockets.emit('news/1', msg.content.toString());

PhoneGap sockets-for-cordova quit app

I have a PhoneGap application and I want to open a socket to a endpoint using sockets-for-cordova plugin:
var socket = new Socket();
socket.open(
"192.168.2.1",
80,
function () {
// invoked after successful opening of socket
console.log("connection");
$scope.$apply();
},
function (errorMessage) {
// invoked after unsuccessful opening of socket
console.log("error");
$scope.$apply();
socket.shutdownWrite();
});
After I use this function to handle messages
socket.onData = function (data) {
// received message
}
On Android it works well, sending and receiving message, unfortunately on iOS it simply doesn't work, not receive any message at all or it close the socket itself.
I can see "connection" message, so I guess that the socket is created.

Connection time out using local broker

I've downloaded Mosca (^1.1.2), MQTT (via npm) and Paho. When I create a simple broker as shown here: http://thejackalofjavascript.com/getting-started-mqtt/ (last 3 codes). It works all fine. My problem is when I try to implement client in the browser using Paho. with this code:
// Create a client instance
var client = new Paho.MQTT.Client('127.0.0.1', 4883, "clientId-1");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
var options = {
//connection attempt timeout in seconds
timeout: 3,
//Gets Called if the connection has successfully been established
onSuccess: function () {
console.log("onConnect");
client.subscribe("testtopic/#");
},
//Gets Called if the connection could not be established
onFailure: function (message) {
console.log("Connection failed: " + message.errorMessage);
}
};
// connect the client
client.connect(options);
// called when the client connects
function onConnect() {
console.log("onConnect");
client.subscribe("testtopic/#");
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log(message.payload);
}
I always get this message: "Connection failed: AMQJSC0001E Connect timed out."
When I change '127.0.0.1' to a online broker, it works. So, I'm guessing my problem is with allowing ports in my broker.
Does anyone know how to solve this problem?

Spray.IO Stop http server with Http.Unbind

I have an app built on spray 1.3.3 and I'm trying to stop http server by sending message.
Official documentation says:
Stopping. To explicitly stop the server, send an Http.Unbind command to
the HttpListener instance (the ActorRef for this instance is available
as the sender of the Http.Bound confirmation event from when the
server was started).
Here is how i the start server:
(IO(Http) ? Http.Bind(httpListener, interface = iface, port = port)).map {
case m: Http.Bound => println(s"Success $iface:$port")
case fail : Http.CommandFailed => println(s"Bad try :(")
}
I tried to send message Http.Unbind to httpListener but with no success. Seems to be it's not that actor
May be i need to extract somehow sender ref of Http.Bound message? But how?
Here is my httpListener's head:
class MyHttpListener extends HttpServiceActor {
import context.dispatcher
def receive = runRoute(
path("shutdown") {
get {
actors.httpListener ! Http.Unbind
complete("Stopping server")
}
}
Anyway, i just want to send http request to /shutdown and have my application be down
The sender of the Bound message should be the Spray listener, so when receiving that message you can capture it.
You did not post your full actor so this is a little different but I hope this helps.
class MyStarter extends Actor {
// this will be the listener
var myListener: ActorRef = _
override def preStart(): Unit = {
implicit val system = context.system
IO(Http) ! Http.Bind(...)
}
override def receive: Receive = {
case msg: Bound =>
// when you receive the Bound message it was sent by the listener
myListener = sender()
...
case ... => ...
}
}

Resources