0

i'm trying to write a socket-server program to send keyboard inputs from my PC to my Raspberry Pi, but when i create a new thread for a function, that has a while loop in it, the script execution does not continue as expected, instead it is stuck. These are my scripts:

import socket
import threading

class Server:
    def __init__(self, host: str, port: int):
        self.host = host
        self.port = port
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind((host, port))
        self.server.listen()
        self.client = None
        self.message = ""

    def stream(self):
        while True:
            self.client.send(self.message.encode('utf-8'))

    def run(self):
        while True:
            print('Server is running and listening ...')
            self.client, address = self.server.accept()
            print(f'Connection is established with {str(address)}')
            thread = threading.Thread(target=self.stream)
            thread.start()
from server import Server
import threading

server = Server('192.168.178.30', 8001)
thread = threading.Thread(target=server.run)
thread.start()

while True:
    try:
        print("A")
    except KeyboardInterrupt:
        break

When i executed the second program it didn't output A's, instead only executed, what's in the while loop of the run function of the first script.

1 Answer 1

0

The code works with localhost, but has a few things that need correcting to handle clients properly:

server.py

import socket
import threading
import time

class Server:
    def __init__(self, host: str, port: int):
        self.host = host
        self.port = port
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind((host, port))
        self.server.listen()
        # self.client = None  # not needed.  Need a local client per client thread
        # self.message = ""   # not needed.  Sending a hard-coded message below.

    def stream(self, client, address):  # add arguments
        print(f'Connection is established with {address}')
        while True:
            client.send(b'hello\n')  # Send an actual message
            time.sleep(1)            # Slow things down for demo

    def run(self):
        while True:
            print('Server is running and listening ...')
            client, address = self.server.accept()  # local client value
            # pass arguments to thread
            thread = threading.Thread(target=self.stream, args=(client, address))
            thread.start()

test.py

from server import Server
import threading
import time

server = Server('', 8001)
thread = threading.Thread(target=server.run)
thread.start()

while True:
    try:
        print('.', end='', flush=True)  # Less noisy
        time.sleep(1)                   # slow down for demo
    except KeyboardInterrupt:
        break

Connecting demo:

>>> import socket
>>> s=socket.socket()
>>> s.connect(('localhost', 8001))
>>> s.recv(1024)
b'hello\nhello\nhello\nhello\n'
>>> s.recv(1024)
b'hello\n'

Output from test.py:

C:\>test
Server is running and listening ...
........Connection is established with ('127.0.0.1', 39750)
Server is running and listening ...
...................
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.