D
D
DvorkinFromChaos2021-10-25 00:44:48
Python
DvorkinFromChaos, 2021-10-25 00:44:48

How to solve python socket(connection.close()) problem?

Such a task:
Create a server on sockets that sends a one-dimensional array of 20-bit numbers to the client 100 times, and a client that must count the number of elements of the array with an even number of digits, and send the result to the server. The server checks the answer each time, if it is correct, then it gives the next array, if not, it swears and stops working. When the 100th correct answer is sent, the server sends a hello.
Here is my server code:

import socket
import random

def recvuntil(s, pattern):
    result = b""
    while pattern not in result:
        result += s.recv(1)
    return result

server_address = ('0.0.0.0', 9090)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(server_address)
server_socket.listen(20)
print('server is running, please, press ctrl+c to stop')

connection, address = server_socket.accept()
print("new connection from {address}".format(address=address))

task = "Тебе необходимо посчитать кол-во элементов массива с четным количеством цифр и отправить обратно.И так 100 раз! Удачи :D \n"

connection.send(task.encode())

for i in range(100):
    a = [(str(random.randint(10000000000000000000,99999999999999999999))+str(round(random.random(),random.randint(1,15)))[1:]) for _ in range(random.randint(3, 7))]
    #Да,это странно

    r2 = f"Array {i+1}: {' '.join(map(str,a))}\n"
    connection.send(r2.encode())

    r3 = "Answer >> "
    connection.send(r3.encode())
    count = 0

    for foo in a:
        b=foo.replace(".","").strip()
        if len(b)%2 == 0:#проверка на чётность
            count+=1

    answer = recvuntil(connection,b"\n").decode().strip()
    
    if int(answer) != int(count):
        r4 = "WRONG *-* \n"
        connection.send(r4.encode())
        connection.close()
       
r5="У тебя получилось !!!\n"
connection.send(r5.encode())
connection.close()


Here is the code for the client:

import socket

def recvuntil(s, pattern):
    result = b""
    while pattern not in result:
        result += s.recv(1)
    return result

HOST = '127.0.0.1'
PORT = 9090

cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
cli.connect((HOST,PORT))
data = cli.recv(1024).decode()
print(data)
for i in range(100):
    array = recvuntil(cli, b">>").decode().strip().split("\n")[:-1]
    array1 = " ".join(array)[8:]
    array1 = array1.split(' ')
    array1 = array1[1:]
    count = 0
    for foo in array1:
        b=foo.replace(".","").strip()
        if len(b)%2 == 0:#проверка на чётность
            count+=1+1# это специально, чтобы вызвать ошибку
    answer = str(count)+"\n"
    cli.send(answer.encode())

print(cli.recv(1024).decode())
print(cli.recv(1024).decode())


In general, the code works, but if the correctness is broken (that is, it enters if ), then connection.close() does not work and the loop continues to work. This is the problem, how can I make the client get only the message "WRONG *-* \n" and the connection is closed? I would appreciate any help or hints.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alan Gibizov, 2021-10-25
@DvorkinFromChaos

Making a variable on the server is a sign of success. Make counter = 100.
Replace the for i in range loop with a while loop with a decrementing counter and checking for success.
Set success indicator to False if hit in if.
At the end, when printing a success message, do a feature check.

check = True
counter = 100
while check and counter > 0:
    counter -= 1if int(answer) != int(count):
        connection.close
        …
        check = False
if check:
    print("У тебя получилось !!!\n")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question