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

  • 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: https://github.com/aaugustin/websockets – BEVR1337 Feb 24 '20 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 –  Feb 25 '20 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. – BEVR1337 Feb 25 '20 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. – BEVR1337 Feb 25 '20 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 –  Feb 25 '20 at 17:44
  • hie i try on another computer it works i will check if it's the firewall of the other computer or fact that i was usiing edge on the other computer and it works with google chrome. Maybe it doesn't work with edge. Thanks for helping but can you please tell me what browser did you use –  Feb 25 '20 at 17:51
  • I am using Firefox currently. I wrote this all into an answer now that I better understand and was able to run your code successfully. What errors is edge reporting? It's possible that you are having CORS issues which I can help you troubleshoot. – BEVR1337 Feb 25 '20 at 17:53

1 Answers1

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.

BEVR1337
  • 623
  • 4
  • 10
  • 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 –  Feb 25 '20 at 18:23
  • 1
    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. – BEVR1337 Feb 25 '20 at 18:28
  • 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 –  Feb 25 '20 at 19:25
  • 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. – BEVR1337 Feb 25 '20 at 19:45
  • thanks, i will try and let ou know. I really appreciate that you help me –  Feb 25 '20 at 19:53
  • it didn't work i've put picture if it may help you . Thanks –  Feb 25 '20 at 20:23
  • Oops, I can't read that language but let me circle back around to this when I am on a windows machine so I can better understand. I'll update my answer then :) – BEVR1337 Feb 25 '20 at 20:24
  • A sorry for the language,i will try to help you –  Feb 25 '20 at 21:10
  • hie, do you need help to do the traduction or not i do not care of doing it at the same time can you answer this question what is the part that connect and the part that receive the message i try by putting after the line`ws.onmessage = function(event) {` the fonction ws.send(" ") but it didn't work i change correctly the python serveur but it work when i first receive and after send but not send and after receive. is it the write place or not please answer and don't tell me to do another question i don't think it's use full t would take some storage for nothing on stack overflow serveur –  Feb 26 '20 at 21:11