How does Socket tcp server receive data?

in the process of learning the python socket module, I wrote a simple server to receive information. I used socke.recv (10) to receive a long string through a loop and put all the data together, but I couldn"t quit the while loop. Please help me.

< hr >
import socket


class Server(object):
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
    
    -sharp 
    def config(self):
        sever = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  -sharp socket
        sever.bind((self.ip, self.port))  -sharp portip,
        sever.listen(1)  -sharp 
        client, address = sever.accept()  -sharp Tcp 
        temp=b""
        info = client.recv(10)
        while info:
            temp+=info
            print(temp)-sharptemp
            info=client.recv(10)
        -sharp
    sever.close()
Mar.02,2021

the connection mode of tcp should be disconnected by the client, and the server should keep the connection and wait for the next connection


you can print out info each time to see the value

.

my guess is that your client is not disconnected, so the server side is blocked in the recv function, and the while loop is not going on all the time

.

the question should be the judgment of while info . You can type out the info to see why it cannot be terminated. Is it equal to exit

?

it is also recommended to optimize as follows:
Server loop, modify the logic, and it is recommended to use multi-threading. Otherwise, a single thread cannot accept connections from other clients while processing connections.

while True:
    -sharp :
    sock, addr = s.accept()
    -sharp TCP:
    t = threading.Thread(target=tcplink, args=(sock, addr))
    t.start()
    
def tcplink(sock, addr):
    print 'Accept new connection from %s:%s...' % addr
    sock.send('Welcome!')
    while True:
        data = sock.recv(1024)
        time.sleep(1)
        if data == 'exit' or not data:
            break
        sock.send('Hello, %s!' % data)
    sock.close()
    print 'Connection from %s:%s closed.' % addr
Menu