websocket server rejects client connection | using python websockets API to connect - python-3.x

so I'm using websockets api python to connect to a server, here is my main logic, to connect to the server and send a heartbeat message to complete the initial handshake, but the server rejects the connection even before I send the heartbeat. The url format mentioned by the website is as follows:
"'wss://<<host_name>>/app/socket?auth=' + authToken "
authToken: String A base64 encoded string of CLIENT_ID
async def listen(self, client_id):
client_id_bytes = client_id.encode('ascii')
url = f"{socket_url}/app/socket?auth={base64.b64encode(client_id_bytes)}"
print(url)
async with websockets.connect(url) as ws:
await self.heart_beat(ws)
while True:
msg = await ws.recv()
print(msg)
my url on printing: wss://<<host_name>>/app/socket?auth=b'<<auth_token>>
error : websockets.exceptions.InvalidStatusCode: server rejected WebSocket connection: HTTP 401
can someone help me understand what may be missing here, thanks in advance

Related

Python websocket server keeps closing

I made a very simple echo websocket server in python:
import asyncio
import websockets
clients = set()
async def server(websocket, path):
print("Client connected")
clients.add(websocket)
try:
async for message in websocket:
print(f"Received message: {message}")
# Echo message to all clients
for client in clients:
if client != websocket:
await client.send(message)
finally:
clients.remove(websocket)
print("Client disconnected")
start_server = websockets.serve(server, "0.0.0.0", 8080, ping_interval=11, ping_timeout=11)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
The problem is that after some seconds running, it closes with this exception:
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedError: sent 1011 (unexpected error) keepalive ping timeout; no close frame received
Things I have tried:
send ping every 8 secs in the client app, still server closes
do not give ping_interval=11, ping_timeout=11 parameters in websockets.serve call so it runs forever
even shorter ping from client app every 5 secs
Nothing seems to work to keep the websocket connection permanently open.

I am getting the error WinError 10057 in python 3.10.1 as I use it for sockets

I am new to network programming in python and I am trying to create a payment gateway for a project. I have run into an error with sending and receiving data between servers.
Here is my code for both the server and the client:
Server Script:
import socket
banka_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
banka_socket.bind(("192.168.0.22", 8082))
banka_socket.listen()
print("Waiting for bank A socket...")
connection_socket, address = banka_socket.accept()
print("Bank A connected")
message = banka_socket.recv(1024).decode()
print(message)
Client Script:
import socket
gateway_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
gateway_socket.connect(("192.168.0.22", 8082))
print("Gateway connected")
client_data = "hello"
message = client_data.encode()
gateway_socket.send(message)
The data is being sent and received on the same computer. I ran the server script and then I ran the client script. That's when I received the following error:
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
The code with the error was:
message = banka_socket.recv(1024).decode()
Please let me know how I fix my code, I've been struggling with this for a while now.

How to solve 401 Unauthorized error in Socket.IO Django framework?

I am trying to get the Socket.IO work with my Django server. Here is my setup:
Frontend js:
const socket = io.connect('127.0.0.1:8001');
socket.on('connect', () => {
console.log('socket id: %s\n', socket.id);
});
Django server:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
sio = socketio.Server(async_mode='eventlet', cors_allowed_origins='*', logger=True, engineio_logger=True)
#sio.event
def connect(sid, environ, auth):
print('connect ', sid, auth)
static_files = {
'/public': './static',
}
application = socketio.WSGIApp(sio, application, static_files=static_files)
eventlet.wsgi.server(eventlet.listen(('', 8001)), application)
Dependencies
Django==2.2.11
django-cors-headers==3.0.0
eventlet==0.30.0
gunicorn==19.7.1
python-socketio==4.6.1
...
When I run the js, the server will return 401 unauthorized error before reaching the connect function.
Frontend:
GET http://127.0.0.1:8001/socket.io/?EIO=3&transport=polling&t=NYKlRjO 401 (UNAUTHORIZED)
Django server log:
(11053) accepted ('127.0.0.1', 34906)
127.0.0.1 - - [02/Apr/2021 15:39:31] "GET /socket.io/?EIO=3&transport=polling&t=NYKlTB8 HTTP/1.1" 401 253 0.002482
But the weird thing is if I commented out the connect event, everything like other events work just fine:
# #sio.event
# def connect(sid, environ, auth):
# print('connect ', sid, auth)
The Django server is running on the same port 8001. I don't think there is any authentication check on the connect event or on the socket. Anyone knows why if I setup the connect event and the socket suddenly stop working?
It took me hours to figure this out because of the server response code is irrelevant to the issue here.
The problem is, for my case, when the js trying to connect to the socket server, there is no auth argument so the connect function will raise an exception cases the connection to fail, while all exceptions raise from the conncet function will result in 401 unauthorized although it may not be the authorization issue.
The fix is simple, change the connect definition to:
#sio.event
def connect(sid, environ, auth=''):
print('connect ', sid, auth)
will address the issue. Always assing auth token from the frontend js is a good idea as well.

Error in server-running while acessing web-page

We are assigned to write a simple app including three pages + mainpage that is going to have links to all other pages (content cut for the version here). Below is fully-functional code, that accomplishes all of that. Nevertheless there is an error randomly arising while running server, which, however, does not affect the work of the server at all.
I have tried to look at what is going on with the requests sent to the server and it showed me that periodically instead of one request, server receives two
import socketserver
from server import ThreadedTcpServer
from request import Request
from response import Response
class MyTCPHandler(socketserver.StreamRequestHandler):
def handle(self):
print('Connected from: ' + str(self.client_address))
print('==========Request===========')
request = Request(self.rfile)
print(request.request_line + '\n')
response = Response(self.wfile)
response.add_header('Content-Type', 'text/html')
response.add_header('Connection', 'close')
if request.path == '/':
...
response.send()
ThreadedTcpServer.allow_reuse_address = True
server = ThreadedTcpServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
server.server_close()
In the log of the server I expect to see only request_lines and print of connection info,but sometimes instead of one request it shows two from different client_addresses and two arising exceptions like:
Connected from: ('127.0.0.1', 34962)
==========Request===========
GET /three HTTP/1.1
Connected from: ('127.0.0.1', 34966)
==========Request===========
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 34966)
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 34962)
and huge traceback starting from socketserver module and ending up in my request class where it cannot parse request_line.

I'm trying to make chat program using Python 3.6 but I think I can't retain connection

import socket
host = 'address' # as you know this isn't letters but I just write it as address for now.
port = 50000
bufsize = 1024
server = socket.socket()
server.bind((host, port))
server.listen(5)
while 1:
print("Waiting Connection")
client, address = server.accept()
print("Connected")
welcomemsg = ("send messages")
client.send(bytes(welcomemsg, "utf-8"))
print("client info")
print(address)
msgfromclient = server.recv(bufsize).decode("utf8")
client.send(bytes(msgfromclient, "utf-8"))
import socket
bufsize = 1024
client = socket.socket()
while 1:
client.connect(('address', 50000))
welcomemsg = client.recv(bufsize).decode("utf8")
print(welcomemsg)
msgtoserver = input()
server.send(bytes(msgtoserver, "utf-8"))
msgfromserver = client.recv(bufsize).decode("utf8")
print(msgfromserver)
I think I can connect server and client and then I can make server send a welcome message to client and client can receive that message.
But after that I think I can't retain connection between server and client any longer.
I want to make server and client retain connection after server send a welcome message to client and client send a message to server and then server send it again to all the clients (yes I am trying to make chat program.)
I am using Windows.

Resources