Is it possible to connect to a Python socket server with Javascript?

  browser, http, javascript, python, websocket

I’m creating a Python socketserver using the module socketserver:

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    def setup(self):
        pass
    def handle(self):
        pass
with socketserver.TCPServer(("localhost", 4000), MyTCPHandler) as server:
    server.serve_forever()

I’ve used the Python module websockets and I could access the websocket in Javascript using the WebSocket API. Without fully understanding what the Python module socketserver really does, I attempted to connect to the TCP socketserver using a websocket:

var socket = new WebSocket('ws://localhost:4000'); // ERROR: Firefox can’t establish a connection to the server at ws://localhost:4000/.

Everytime, Firefox threw the error Firefox can’t establish a connection to the server at ws://localhost:4000/. Then, I tried connecting to the server using the Python http module:

import http.client
httpConnection = http.client.HTTPSConnection("localhost:4000", timeout=10)
print(httpConnection) # HTTP Connection Object

Sadly, this worked. Now, I understand that Python’s built-in socketserver module creates can only be accessed through HTTP. Now, I want to know if it is possible to connect to a Python TCP socketserver with Javascript in the browser. If not, I’ll just use websockets or figure out how to create my own websocket.

Source: Python Questions

LEAVE A COMMENT