How does the Python module socket stop when it receives empty data?

< H2 > question < / H2 >

Python"s module socket uses ecv () to constantly listen to the request data sent by the client, including the empty string bounded". How to identify the empty request and block it?

< H2 > Source code < / H2 >

Server side:

import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 8080))
server.listen(50)
while True:
    data, addr = server.accept()
    info = b"OK"
    while True:
        buffer = data.recv(2)    -sharp  b""
        if buffer == b"":
            info = b"Bad request"
            break
    data.send(info)
    data.close()

client:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 8080))
data = b""
s.send(data)
data_get = s.recv(1024)    -sharp 
s.close()
Apr.09,2021

Port 8080 of your client bind and port 80 of server bind are inconsistent, so change it first.

s.send(b'') -sharp''0tcpprint(buffer)
s.send(b'123') -sharpbuffer2b'12'b'3'

socket.recv () is a blocking function that waits all the time without receiving any data. When you send an empty character, you actually don't send a character.
in practical applications, this part of the function is usually thrown into a child thread to execute, so that your main thread can do other things while waiting to receive.


if the read blocking socket returns an empty string, the connection is over.

you can switch to non-blocking socket, or use python3's asyncio.

refer to python.org/3/library/asyncio-protocol.html-sharptcp-echo-server-protocol" rel=" nofollow noreferrer "> https://docs.python.org/3/lib.


assume that `data is the value sent by the client
if data=='':

`
when TCP waves four times, a null value will be sent at last, but there is no such type in python. All python will be interpreted as a''string. You need to know that null is not equal to an empty string.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1bedd6e-39f59.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1bedd6e-39f59.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?