I have a server where a server socket accepts connections and sends no. of clients connected. I can connect to it fine with Java and Python websocket programs and it gives the desired client no. count, but JS websocket gives error.
Server code:
import socket
import threading
import time
lock = threading.Lock()
count = 0
def handle_client(c: socket.socket, addr):
global count, lock
while True:
try:
c.send(f"{count}".encode())
time.sleep(0.5)
except:
print('Client disconnected: ' + addr[0])
with lock:
count -= 1
break
s = socket.socket()
port = 56123
s.bind((socket.gethostname(), port))
s.listen(5)
print('Server started')
while True:
c, addr = s.accept()
print('Client connected: ' + addr[0])
with lock:
count += 1
threading.Thread(target=handle_client, args=(c, addr,)).start()
Python client code:
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('server.com', 56123))
while True:
print(s.recv(1024).decode())
time.sleep(5)
JS client code:
const ws = new WebSocket('wss://server.com:56123');
ws.onmessage = (msg) => {
console.log(`Live users: ${msg.data}`);
};
ws.onerror = (err) => {
console.error(err);
}
setTimeout(() => {
console.log('ok')
}, 1000);
JS client error:
ErrorEvent {
type: 'error',
defaultPrevented: false,
cancelable: false,
timeStamp: 2791.141283
}
I originally intend to use this JS code to show the count on a HTML site. When I did that I got the following error:
WebSocket connection to 'wss://server.com:56123/' failed:
Your problem is that you are creating a regular network socket in Python and are trying to connect to it through the JS client as if it is a WebSocket, WebSockets are not the same as sockets and are not compatible with each other. You can fix this by instead using a WebSocket server in Python using the WebSocket library for both the server and client. e.g:
import websockets