Why wont my websocket channels connect on mobile ?

I am on the same network as my local server running on desktop.

it connects fine on desktop and sends and reciieves the data back,

but on mobile it does not and no error is also shown, what could be the problem ?

Surprisingly i juct tried to connect with HTMX, and it connects with htmx using the below code, in my terminal it shows the output as connected

<div hx-ext="ws" ws-connect="/ws/justtesting/" id="websocket">
</div> 

consumers.py file

class JustTesting(AsyncWebsocketConsumer):

async def connect(self):

    self.user = self.scope['user'] if self.user.is_anonymous:
    self.close()

else:

    await self.accept() 
    print(f"{self.scope['user']} is connected from {self.scope['client'][0]}")

async def disconnect(self, close_code):

    print(f"{self.scope['user']} is disconnected") 


async def receive(self, text_data):

    text_data_json = json.loads(text_data)
    message = text_data_json['message']

    print(message)

    # Send message back to client

    await self.send(text_data=json.dumps({ 'message': message }))

It’s not clear to me from your question what you are asking here.

Your subject title for this topic asks why won’t your websockets connect on mobile, but the text in your message says that HTMX (using websockets) connects just fine.

I can also confirm (because I’m using it in a production deployment) that HTMX works great with Chrome on both an iPad and a Samsung Android phone.

Are you saying that your JavaScript client for websockets isn’t working? If so, that’s where I would start. In particular, I’d be looking into the possible browser differences for websocket APIs.

(Side note: I strongly recommend against trying to write your own JavaScript websocket code. Find some library that you’re comfortable with and use it.)

hi sorry it wont connect in the mobile, maybe as the the network is same but the ipadress is different ?

are you saying i should not use direct vanilla javascript for websocket connection ?

my JS code.

var surfing_user = document.getElementById("user_surfing").getAttribute("value")
let username;
let spinner;

if (surfing_user !== "AnonymousUser") {

    username = document.getElementsByClassName("profile_username")[0].textContent
    spinner = document.getElementsByClassName("spinner")[0]

if (document.getElementById('earnings-button') !== null){

const money_graphSocket = new WebSocket(
    'ws://' + '0.0.0.0:8000' +
    '/ws/money_earned/'
  );

money_graphSocket.onopen = function(e) {
    console.log("money_graph WebSocket connection established!");

const earningsButton = document.getElementById('earnings-button');


const chartWrapper = document.getElementById('chart-wrapper');

let ctx = document.getElementById("myChart").getContext("2d");

let chartData = {
  labels: [],
  datasets: [
    {
      label: `${username}'s Earnings`,
      backgroundColor: "#79AEC8",
      borderColor: "#417690",
      data: []
    }
  ]
};

let chartOptions = {
  responsive: true,
  title: {
    text: "Gross Volume in 2020",
    display: true
  }
};

let chart = new Chart(ctx, {
  type: "line",
  data: chartData,
  options: chartOptions
});



earningsButton.addEventListener('click', function() {

    spinner.style.display = "block"

    if (earningsButton.textContent !== "Hide Earnings") {

    money_graphSocket.send(JSON.stringify({
        "message": "get_earnings_report",
        }));
    
    money_graphSocket.onmessage = function(e) {
        var data = JSON.parse(e.data)

        spinner.style.display = "None"
        // Update the chart data and options with the fetched data.
        chartData.labels = data.message.labels;
        chartData.datasets[0].data = data.message.data;
        chart.update();

        chartWrapper.style.display = 'flex';
        earningsButton.textContent = "Hide Earnings"
    
    }
  
  } else {
    chartWrapper.style.display = "None";
    earningsButton.textContent = "Your Earnings"
    spinner.style.display = "None"
  
  }
  
  });


}

}
}

SOLVED: i hade to start my python3 manage.pyrunserver with the ipaddress and port(8000) for the mobile and also change my websocket conneting url in JS with the same ipaddress and port.

cheers :slight_smile:

I don’t recommend it, no.

Websockets aren’t perfect - especially on mobile. Depending upon precise usage and the environment you will be using this in, you may experience some number of random disconnects - your software should be written to handle that and to gracefully reconnect when necessary, along with recovering whatever “context” may be appropriate for that connection.

Can you do that in “vanilla javascript”? Sure. But why would you want to? (There’s a reason why people write and publish “websocket-helper” libraries.)

so will using HTMX be a good option ? can you hep me out on the code to recive and send messages to th websocket.

i know how to connect now how to recieve and send messages to my conusmers.py?

<div hx-ext="ws" ws-connect="/ws/justtesting/" id="websocket">
</div> 

Answered in your other thread here: should i use HTMX's hx-target everywhere for my navbar ? - #18 by KenWhitesell

It’s a good option for us. It works extremely well for me. Whether it’s good enough for you will be something only you can decide.

hi so i finally learned how to recive messages from channels using HTMX , now the only part is on how to send specific data back ?

consumers.py

class JustTesting(AsyncWebsocketConsumer):

    async def connect(self):
        
        self.user = self.scope['user']
        if self.user.is_anonymous:

            self.close()

        else:

            await self.accept()
            print(f"{self.scope['user']} is connected from {self.scope['client'][0]}")

            html = get_template("partials/testing_data.html").render(
            context={"username": "Kakashi12345"}
                )
            await self.send(text_data=html)

            await self.send(text_data=json.dumps({
                'type': "Testing socket Established",
                'message': "Testing socket message"
                }))


    async def disconnect(self, close_code):
        print(f"{self.scope['user']} is disconnected")
        pass

my partials html file


<div id = "my_testing_message">
    <b>{{username}}</b>
   </div>

my main html template

{% include "partials/testing_data.html" %}

so the above code succesfully recives the message on connection, but now how to send ?

thanks

What event is going to occur that would require that data be sent?

1 Like

Hi. So i have button with text follow. As soon as I click it it will send the message or text of “follow” back to the Websocket.

And the Websocket will check if the text is follow…

It will send back the text of “Unfollow” and Vice Versa…

And the button will change the text accordingly.

This works perfectly with vanilla js and Websockets.

Now i want to use HTMX instead of JS, so just want to know how to send the data back to the Websocket

Thanks

HTMX works by acting on events. In this case, it’s going to send data as a result of the button click. The mechanics for this is all documented at the locations referenced earlier. Specifically, see websockets extension - </> htmx - high power tools for html.

1 Like

Thanks will check it out :slightly_smiling_face:

so i can finally send messages but how can i send the button wit the text of follow ? i tried the following:

<div hx-ext="ws" ws-connect="/ws/justtesting/" id="websocket">

<form ws-send="">

<button type="submit" name="message" value="follow">Follow</button>

</form> </div>

when i click it i get the following in the terminal

{'HEADERS': {'HX-Request': 'true', 'HX-Trigger': None, 'HX-Trigger-Name': None, 'HX-Target': 'websocket', 'HX-Current-URL': 'http://0.0.0.0:8000/testing/', 'X-CSRFToken': 'ud647GyUx5ikPmXFz8hsdasdasdasd'}}

now i can put

<input type = message>

and then click on the button but that defeats the purpose, i want the user to click it and not type in the message box

You can pass data the same way you would supply data with any other HTMX request. You have all the facilities of HTMX available to you including hx-vars and hx-include.

1 Like

hi below is how i send the data back and got the results i wanted, but is this good practice or shal i do it in some other way if it exists ?

 <div hx-ext="ws" ws-connect="/ws/justtesting/" id="websocket">

  <div id = "my_testing_message">    

  <form ws-send="">

    <input type ="hidden" name ="message" value="follow">
    <button class = "btn btn-primary" type="submit"  value="follow">Follow</button>

</form>  

 </div> 


</div>

If it works for you, then it’s “good”.

I don’t think HTMX has been around long enough for there to have been the formation of a consensus of “best practices”. The different ways of doing things have advantages and disadvantages, making the selection here a bit of an “it depends” situation. (And, it’s still a bit of an evolving environment, so answers may still change in the future.)

thanks a lot and i just want to ask you why my page refreshes when i unfollow a user ?

so i click the button it follows the user and sens back red color so the bell icon on the navbar becomes red succefulyy

so when i press unfollow it refreshes and removes the red color why is that ?

<div id="notification-icon">

    <i class ="fas fa-bell" style="{{color}}"> <i>

</div>

when i get back the data without setting any color variable from consumers.py it does not refresh and unfollows normally

I don’t know. You aren’t showing an “unfollow” button in the portion of the html posted above.

1 Like

i am sorry, this is my full partials html code

<div id = "my_testing_message">
    <form ws-send="">

        <input type =  "hidden" name ="message" value="{{message}}">
        <button class = "{{button_class}}" type="submit" value="{{message}}">{{message}}</button>
    </form>  

</div>


<div id ="my-username">
    <b>{{username}}</b>
</div>

<div id="notification-icon">

    <i class ="fas fa-bell" style= "position: relative;
    {{color}};
    margin-right: 10px; 
    font-size: 2em";> <i>


</div>

I’m assuming that you’re replacing the contents of the button between the follow and unfollow versions?

What do the complete contents of the <div id="my_testing_message">...</div> look like in the browser for the two versions?

(Side note: When using a button to trigger an htmx-related action, you generally want it to be type="button", not type="submit". You are not submitting the form by the browser.)

1 Like