'Interacting with the server via socket
There is a server that gives a welcome message and the first simple arithmetic problem in Chinese when you connect to it:
欢迎来到中文房间
你必须解决成千上万的案件
九加零
The first two lines are permanent. They are given at each new connection and do not change. At the same time, the task text (the last line) is different every time. It has either 3 or 5 characters. In the first case, the 1st and 3rd character are numbers from 0 to 9, the 2nd character is a + or - operator. In the second case, the first two characters stand for a module. I have written a code containing a solution function. But I have a problem with passing the answer and getting a new problem. The thing is that after solving the nth task in the answer I have to get the key instead of the task.
import socket
letters = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七'
, '十八', '十九', '二十']
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
ops = {'加': '+', '减': '-'}
chinese2num = dict(zip(letters, numbers))
num2chinese = dict(zip(numbers, letters))
def answer(data):
task = data
if len(task) == 30:
task = task[24:29]
elif len(task) == 28:
task = task[24:27]
else:
print(f'flag: {data}')
return False
if len(task) == 5:
num1 = task[2]
num1 = chinese2num[num1]
operation = task[3]
operation = ops[operation]
num2 = task[4]
num2 = chinese2num[num2]
if operation == '+':
result = num1 + num2
if operation == '-':
result = num1 - num2
result = abs(result)
result = str(result)
print(result)
return result
elif len(task) == 3:
num1 = task[0]
num1 = chinese2num[num1]
operation = task[1]
operation = ops[operation]
num2 = task[2]
num2 = chinese2num[num2]
if operation == '+':
result = num1 + num2
if operation == '-':
result = num1 - num2
result = num2chinese[result]
result = str(result)
print(result)
return result
sock = socket.socket()
sock.connect(('<ip>', <port>))
n = True
while n:
data = sock.recv(1024).decode()
print(data)
ans = answer(data)
if ans == False:
break
else:
sock.send(ans.encode())
sock.close()
I'm stuck at the stage where I get the second task. That is, I sent the solution, the connection is not broken, but I can't get a new task.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
