1

i want that the serveur connect and send data to the python serveur but unfortunately i have this errorSCRIPT12029: SCRIPT12029: WebSocket Error: Network Error 12029, i have seen on this website Connecting to TCP Socket from browser using javascript at the second post when he says You can use also attempt to use HTML5 Web Sockets (Although this is not direct TCP communication): so this is the java script html code

<!DOCTYPE html>
<html>
<head>
    <title>JS #0</title>
</head>
<body>
    <script>
        try{
            var connection = new WebSocket('ws://127.0.0.1:1555');

            connection.onopen = function () {
                connection.send('Ping'); // Send the message 'Ping' to the server
            };
        }catch(Exception){
        }
                </script>
</body>
</html>

python

# coding: utf-8

import socket

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
a=1
if(a==1):
    try:

        socket.bind(('', 1555))


        socket.listen(5)
        print("client start")
        client, address = socket.accept()
        print ("{} connected".format( address ))

        response = client.recv(255)
        if response != "":
                print(response)
    except Exception as e:
        print(e)
    finally:
        socket.close()

Second try

#!/usr/bin/env python

# WS server that sends messages at random intervals

import asyncio
import datetime
import random
import websockets

async def time(websocket, path):
    while True:
        now = datetime.datetime.utcnow().isoformat() + "Z"
        await websocket.send(now)
        await asyncio.sleep(random.random() * 3)

start_server = websockets.serve(time, "127.0.0.1", 5678)

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

and the html code

<!DOCTYPE html>
<html>
    <head>
        <title>WebSocket demo</title>
    </head>
    <body>
        <script>
            var ws = new WebSocket("ws://127.0.0.1:5678/"),
                messages = document.createElement('ul');
            ws.onmessage = function (event) {
                var messages = document.getElementsByTagName('ul')[0],
                    message = document.createElement('li'),
                    content = document.createTextNode(event.data);
                message.appendChild(content);
                messages.appendChild(message);
            };
            document.body.appendChild(messages);
        </script>
    </body>
</html>

have i done wrong or it's not the right code, i have found the code on this website https://websockets.readthedocs.io/en/stable/intro.html

new photo of error with Microsoft edge. error Microsoft edge picture

configuration with about:flagsimage second post answer of the website give in the awnserimage 1 menu setting imag2 setting detecter automaticement le reseau intranet= automatically detect the intranet network

7
  • Socket is a low-level library for reading and writing to sockets. Browsers can only use websockets, a protocol built on top of the sockets you want to use. If you want to talk to a browser, try a websockets library like this one: github.com/aaugustin/websockets Commented Feb 24, 2020 at 15:25
  • hie, i have done some update with the new code in the part second try is it normal or not that it still doesn't work and it can't connect may i not understand your answer and you say that it's not possible okay. but if websocket can't do it do you know a website that explain normal socket in java script or they are no normal socket. normal socket is the sockett like python Commented Feb 25, 2020 at 17:16
  • The issue in your new code is a user error, not an issue with websockets. You MUST use a websocket library if you want a socket connection with the browser, there's no way around that. You can opt to implement the protocol manually using a raw socket, but that sounds undesirable. Commented Feb 25, 2020 at 17:29
  • 1
    Your new code works just fine for me by the way! I have an html page with a list of timestamps as desired. Commented Feb 25, 2020 at 17:42
  • hie thanks to help me can you say where do you execute it because for me i execute my pyhon code in a the CMD and it doesn't work Commented Feb 25, 2020 at 17:44

1 Answer 1

1

Not the world's best answer, but hopefully this will get you on track!

Browsers do not support raw sockets, but they do support one specific socket protocol, WebSockets. WebSockets are built on top of TCP/IP and are a great, easy way to form long-lived connections between a browser and another machine. Because your code was originally utilizing raw sockets, the browser was never going to perform a handshake. Now that you've changed your answer to support websockets, you're closer than ever!

I'm not sure what issue you're experiencing with your new code because it works perfectly for me. I made a few modifications since I am running a lot of dev environments and I can't have StackExchange debugging interfering. Here's my code which only has 3 changed lines from yours:

<!DOCTYPE html>
<html>
  <head>
    <title>WebSocket demo</title>
  </head>
  <body>
    <script>
      var ws = new WebSocket('ws://127.0.0.1:5678/'),
        messages = document.createElement('ul');
      ws.onmessage = function(event) {
        var messages = document.getElementsByTagName('ul')[0],
          message = document.createElement('li'),
          content = document.createTextNode(event.data);
        message.appendChild(content);
        messages.appendChild(message);
      };
      document.body.appendChild(messages);
    </script>
  </body>
</html>

#!/usr/bin/env python3

# WS server example
import sys
# forcibly adding a path for the following libraries
# this is probably not necessary on anyone else's machine,
# but I need it just for testing this answer
sys.path.append('/usr/local/lib/python3.7/site-packages')
import asyncio
import websockets
import datetime
import random

async def time(websocket, path):
    while True:
        now = datetime.datetime.utcnow().isoformat() + "Z"
        await websocket.send(now)
        await asyncio.sleep(random.random() * 3)

start_server = websockets.serve(time, "127.0.0.1", 5678)

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

And it works great: Screenshot showing how well your code is working!

I saved your python script as foo.py and the html document as bar.html to my desktop. To start the python server, I ran python3 foo.py from the command line, and then I opened the html file using my preferred browser, no http servers were required for this example.

What errors are you seeing in the browser or console that are prohibiting this from working?

Error 12029 is the error OP is seeing! By default, Edge will not listen on local interfaces, e.g. localhost and 127.0.0.1. This thread on Microsoft.com has some troubleshooting advice for developers using Edge. Let us know if these configurations are helpful.

Sign up to request clarification or add additional context in comments.

9 Comments

it's normal that it works with you it also works with me the problem was that i had this error with Microsoft Edge you can try our side it will work with Gogle Chrome or Mozilla but i don't know why it doesn't work with Microsoft Edge? Sorry for wasting our time and thank. Goodbye
Not wasting my time at all! I suspect Edge is giving you CORS errors. If you can show me the errors Edge produces, I would be glad to continue the troubleshooting and updating my answer. Good luck.
ok this is my error SCRIPT12029: SCRIPT12029: WebSocket Error: Network Error 12029, Unable to connect with server and i put a photo on the main question
After doing some digging, Edge does not allow listening to localhost by default. I found a thread and blog post with more details, added a link to the answer.
thanks, i will try and let ou know. I really appreciate that you help me
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.