S
S
sparr0w12021-09-07 22:37:45
Python
sparr0w1, 2021-09-07 22:37:45

How to stop "Space" spam on the server after closing the client?

I made a small local chat, but after the Client part is closed, "Space" spam starts on the server. How can this be fixed?

server

host = socket.gethostbyname_ex(socket.gethostname())[-1][-1]
        port = 6677

        print(socket.gethostbyname_ex(socket.gethostname()))
        print(host)
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind((host, port))
            s.listen()
            while True:
                conn, addr = s.accept()
                while True:
                    data = conn.recv(1024).decode('utf-8').lower()
                    print(data)

client
import socket

HOST='192.168.0.13'
PORT= 6677

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))

    while True:
         s.send(input().encode('utf-8')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-09-09
@Vindicar

while True:
    data = conn.recv(1024).decode('utf-8').lower()
    print(data)

At you the server does not provide an output from service of the client at all. Unless by exception, but then the entire server will crash.
You don't check to see if you got anything. If the connection is closed, recv() will return a zero-length bytes object. So check the length, and if it's zero, break the loop.
Also in your code, neither the server nor the client provides for a normal termination of the connection. If you're using TCP, then you need to call the s.shutdown() method to let the other side know that there will be no more data, and then s.close() to completely close the connection.
The client will need to define a condition for when to close the connection. For example, if the user enters an empty string in response to input().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question