Search code examples
pythonsocketsapschedulerpython-sockets

Python Socket - Server Stop after receive only one message


firstly sorry for my bad english (I'm French) because I'm trying to not use Google Translate.

So, my problem is in the following set of server.py and client.py. Just a client that send every 10 seconds a message with a incremental counter on the server.py. I write this script to check if my university work server "live" or "die" after my logout (and for my training).

server.py:

# -*- coding: utf-8 -*-

import socket

HOST = 'localhost'
PORT = 1602

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind(('localhost', PORT))

while True:
        socket.listen(5)
        client, address = socket.accept()
        print(f"{address} connected")

        response = client.recv(1024)
        print(response.decode())

print("Close")
client.close()
socket.close()

client.py:

# -*- coding: utf-8 -*-

import socket
from apscheduler.schedulers.blocking import BlockingScheduler

HOST = 'localhost'
PORT = 1602

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST, PORT))
print(f"Connection on {PORT}")

timeCount = 0

def some_job():
    global timeCount
    timeCount += 1

    print(f"Send N°{timeCount}")
    string = f'Schedule Transmission N°{timeCount}'
    socket.send(f"Schedule Transmission N°{timeCount}".encode())

scheduler = BlockingScheduler()
scheduler.add_job(some_job, 'interval', seconds=5)
scheduler.start()

print("Close")
socket.close()

The problem is that the server side print only (and probably receive only) the first message/first transmission. So, not a problem of encodage and the connexion seems to exist even after the first message print. I understand well the code in itself. I don't see what's the problem. There is any exception or error when running.

Can someone help me, please?

Cordially


Solution

  • I only needed to change your server code. I added multithreading. Now multible clients can connect to the server without blocking the entire process.

    # -*- coding: utf-8 -*-
    
    import socket
    import threading
    
    HOST = 'localhost'
    PORT = 1602
    
    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.bind(('localhost', PORT))
    
    def handle_client(client, addr):
        print(f"[NEW CONNECTION] {addr} connected.")
        connected = True
        while connected:
            response = client.recv(1024)
            if response:
                print(f"[{addr}] {response.decode()}")
    
        client.close()
        
    
    while True:
        socket.listen()
        client, addr = socket.accept()
        thread = threading.Thread(target=handle_client, args=(client, addr))
        thread.start()