Python Forum
ws server exit after getting 1 connection
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ws server exit after getting 1 connection
#1
Hello ,

this is my WS server test
just listen and wait for message with '29' then send "ok" \ "false" acoording to the request

import asyncio
import websockets
import time
from datetime import datetime

async def hello(websocket, path):
    while True:
        print('Got request')
        task = await websocket.recv()
        remote_ip = websocket.remote_address
        print(task)
        if "29" in task:
            print('this is a good reading from  ' + str(remote_ip))
            await websocket.send('Good question!')
        await websocket.send('Wrong question!')

start_server = websockets.serve(hello, "10.0.0.104", 6500)
asyncio.get_event_loop().run_until_complete(start_server) # this for startup the websocket server
print("server started")
asyncio.get_event_loop().run_forever()
and this is the client code:
import asyncio
import websockets
import time

Message = "test 29"


async def hello():
    try:
        async with websockets.connect(uri1) as websocket:
            await websocket.send(Message)
            replay = await websocket.recv()
            print (replay)
    except Exception as e:
        print (e)
        print ('problem sending')

asyncio.get_event_loop().run_until_complate(hello())
on the client side I get the correct messages
Good question!
but on the server side I get this
server started
Got request
Test 29
this is just reading!('10.0.0.104', 45966)
Got request
Error in connection handler
Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.7/site-packages/websockets/server.py", line 191, in handler
    await self.ws_handler(self, path)
  File "/home/pi/Documents/WebSocketServerReadData.py", line 11, in hello
    task = await websocket.recv()
  File "/home/pi/.local/lib/python3.7/site-packages/websockets/protocol.py", line 509, in recv
    await self.ensure_open()
  File "/home/pi/.local/lib/python3.7/site-packages/websockets/protocol.py", line 812, in ensure_open
    raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason
what is wrong?


maybe the sending is wrong ? and I need to make another code to send the data just 1 time ?
Thanks ,
Reply
#2
Remove the while True loop from handler hello, because this function is called from websockets.serve for each new connection.

Server-code:
import asyncio
import websockets
import time
from datetime import datetime


async def hello(websocket, path):
    print('Got request')
    task = await websocket.recv()
    remote_ip = websocket.remote_address
    print(task)
    if "29" in task:
        print('this is a good reading from  ' + str(remote_ip))
        await websocket.send('Good question!')
    await websocket.send('Wrong question!')


start_server = websockets.serve(hello, "localhost", 6500)
loop = asyncio.get_event_loop()
loop.run_until_complete(start_server) # this for startup the websocket server
print("server started")
loop.run_forever()
Client-code:
just assigned loop and using upper case letters for constants.
import asyncio
import websockets
import time

MESSAGE = "test 29"
URI1 = "ws://localhost:6500/"
async def hello():
    try:
        async with websockets.connect(URI1) as websocket:
            await websocket.send(MESSAGE)
            replay = await websocket.recv()
            print (replay)
    except Exception as e:
        print (e)
        print ('problem sending')


loop = asyncio.get_event_loop()
loop.run_until_complete(hello())
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
yes
you are right

I don't know how it got there.......
Confused Confused Confused
Thanks now it's working
Reply
#4
I'm not sure the while loop is the issue. It's a socket, repeated back and forth communication is to be expected, so multiple socket.recv() calls should work. The issue looks like the client just quits once it receives a response from the server. So instead of while True: sock.recv(), use a try/except block, so the server doesn't crash when clients disconnect.

OR! https://websockets.readthedocs.io/en/sta...ne-message

You can just iterate over the socket, and the iterator will handle disconnecting clients for you.
async def hello(websocket, path):
    print('Got request')
    remote_ip = websocket.remote_address
    async for task in websocket:
        # no longer needed
        # task = await websocket.recv()
        print(task)
        if "29" in task:
            print('this is a good reading from  ' + str(remote_ip))
            await websocket.send('Good question!')
        await websocket.send('Wrong question!')
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Networking Issues - Python GUI client and server connection always freezes Veritas_Vos_Liberabit24 0 734 Mar-21-2023, 03:18 AM
Last Post: Veritas_Vos_Liberabit24
  python difference between sys.exit and exit() mg24 1 1,847 Nov-12-2022, 01:37 PM
Last Post: deanhystad
  Mysql error message: Lost connection to MySQL server during query tomtom 6 16,098 Feb-09-2022, 09:55 AM
Last Post: ibreeden
  pysql connection to cloud server database times out Pedroski55 9 4,741 Oct-11-2021, 10:34 PM
Last Post: Pedroski55
  Serial connection connection issue Joni_Engr 15 8,080 Aug-30-2021, 04:46 PM
Last Post: deanhystad
  How to take the tar backup files form remote server to local server sivareddy 0 1,906 Jul-14-2021, 01:32 PM
Last Post: sivareddy
  Connection timed out error when connecting to SQL server kenwatts275 2 3,344 Jun-02-2020, 07:35 PM
Last Post: bowlofred
  Connection with SQL Server DionisiO 0 2,113 Jan-27-2019, 01:11 PM
Last Post: DionisiO
  Windows server 2008 SP2 - Python cx_Oracle connection DLL error tpanagoda 2 5,058 Mar-05-2018, 04:35 AM
Last Post: tpanagoda
  Problem with connection: Python + SQL Server carlos_123 2 5,245 Feb-13-2018, 06:13 PM
Last Post: carlos_123

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020