root
root

Reputation: 137

Pass arguments to websocket in Django

When working with websockets, how do I pass arguments to the server side from the browser? I want to return Hello, from the server when the browser makes a WS request. The shall be passed from the client.


JavaScript run in the browser.

var socket = new WebSocket('ws://<IP>:80/ws/hello/');
        socket.onmessage = function(event){
        var data = JSON.parse(event.data);
         console.log(data);
}

The routing.py

from django.urls import path
from .consumers import *

ws_urlpatterns = [
    path('ws/hello/', Hello.as_asgi())
]

The consumers.py

from channels.generic.websocket import WebsocketConsumer
class Hello(WebsocketConsumer):
    def connect(self):
        self.accept()
        self.send(json.dumps({'message':"Hello, <NAME>!"}))

How do I get the NAME to be replaced with the client's name?

Can I in the JavaScript code use

var socket = new WebSocket('ws://<IP>:80/ws/hello/?<NAME>');

When I do that, how do I pass the name to the Hello class in consumers.py and shall I add something special in routing.py?

Upvotes: 0

Views: 1473

Answers (1)

johnnyApplePRNG
johnnyApplePRNG

Reputation: 68

To send data to a websocket server, you want to use socket.send('string to send')

See : https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications#sending_data_to_the_server

No need to edit the websocket connection URI.

To change NAME just make that section of string a python variable, and change that variable's value to whatever you want.

Upvotes: 1

Related Questions