question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Websocket + localhost Webview not working (code:1006)

See original GitHub issue

Specification

  • Platform: Linux
  • Version: Python3.5 / v2.0.3

Description

Hi everyone,

I have a big issue, I attempt to use a websocket to communicate between the webview and my python software.

  • If run the webpage (websocket client) not in the pywebview it works (ws://localhost:8080).
  • If I use pywebview and another websocket server address (not localhost), (e.g: wss://echo.websocket.org/) it works too

But: No matter the port if I use local server (localhost) + start the webpage client with pywebview

I try to update the header of the websocket server (in case of CORS error):

headers["Access-Control-Allow-Origin"] = "*"
headers["Access-Control-Allow-Headers"] = "origin, x-requested-with, content-type"
headers["Access-Control-Allow-Methods"] = "PUT, GET, POST, DELETE, OPTIONS"

But it’s not working neither.

Here the Python code:

# https://websockets.readthedocs.io/en/stable/

import asyncio
import websockets

async def hello(websocket, path):
    name = await websocket.recv()
    print("Msg received from the client: '{}'".format(name))
    msg = "Hello {}!".format(name)
    print("Msg sending to the client: '{}'".format(msg))
    await websocket.send(msg)
    print("Msg sent")


headers = websockets.http.Headers()
headers["Access-Control-Allow-Origin"] = "*"
headers["Access-Control-Allow-Headers"] = "origin, x-requested-with, content-type"
headers["Access-Control-Allow-Methods"] = "PUT, GET, POST, DELETE, OPTIONS"

start_server = websockets.serve(hello, '127.0.0.1', 8080, extra_headers=headers)

import webview
import traceback

try:
	webview.create_window("Test wewbsocket & webview", "file:///home/xxx/test_websocket.html")
except:
	print(traceback.format_exc()[:-1])

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

The js code:

function add_message(source, message) {
    var li_elem = document.createElement("li");
    var span = document.createElement("span");
    span.setAttribute("class", source);
    span.innerHTML = message;
    li_elem.appendChild(span)
    document.getElementById("messages").appendChild(li_elem);
}

function send_message(socket, message) {
    add_message("client", message);
    socket.send(message);
}

function receve_message(message) {
    add_message("server", message);
}

function connect_to_server() {
    // var socket = new WebSocket("ws://localhost:8765");
    var socket = new WebSocket("ws://localhost:8080");
    add_message("system", "Init server");

    socket.onopen = function(event) {
        send_message(socket, 'Test de message');
        /* setTimeout(function() {
            socket.send();
        }, 1000); */
    };

    socket.onmessage = function(event) {
        add_message("system", "Message receving");
        receve_message(event.data);
    }

    socket.onerror = function(event) {
        add_message("system", "Error with the server: " + JSON.stringify(event));
    }

    socket.onclose = function(event) {
        add_message("system", "Connection closed with the server: " + JSON.stringify(event));
        setTimeout(function() {
            add_message("system", "Reconnecting attempt");
            connect_to_server();
        }, 2000);
    }
}

window.onload = function() {
    connect_to_server();
}

Any idea?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
delbos-dcommented, Aug 8, 2018

The interesting thing is if I split the python file (socket server in one and the webview in the other file) it works (the webpage communicate with the socketserver without any error).

I will try to use a webserver, but I try to limit the resources used (it’s why I use a webview)

0reactions
r0x0rcommented, Aug 15, 2019

The issue was solved here https://github.com/r0x0r/pywebview/issues/370 I am closing this ticket

Read more comments on GitHub >

github_iconTop Results From Across the Web

Websockets in WebViews failing to connect, returning code ...
However, when I load it in a web view like in an Android App it fails to connect and returns the code 1006....
Read more >
iOS 15 WKWebView websocket behaviour
Problems like this, where code worked on a previous OS release but fails on a beta seed of a new OS, are always...
Read more >
WebSockets Standard
A WebSocket server that sent a correct opening handshake, but that specified options that caused the client to drop the connection (e.g. the ......
Read more >
WebSocket: error event - Web APIs | MDN
The error event is fired when a connection with a WebSocket has been closed due to an error (some data couldn't be sent...
Read more >
Posts • Hybrid Web Apps • Neptune Software Community
Webview does not implement Webauthn API on Certificates, devices are shared and we do not ... "Failed to connect to Websocket: code: 1006,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found