Python Tic Tac Toe с розетками - проблемы с розетками - PullRequest
1 голос
/ 07 октября 2019

Я пытаюсь написать игру Tic Tac Toe с сокетами на python. Есть файл сервера и файл клиента. Когда я запускаю его (в настоящее время все на моем компьютере), я запускаю файл сервера, а затем дважды запускаю файл клиента (для X и для O). В какой-то момент я получаю ошибку сокета (указанную позже в комментарии в коде из файла сервера).

Это основной метод в файле сервера:

~~ python

mat = initialize() # initializes the board (a matrix)

server_socket = socket.socket()
server_socket.bind(("0.0.0.0", 5555))
server_socket.listen(2)
(ix_socket, client_address) = server_socket.accept()
(o_socket, client_address) = server_socket.accept()

ix_socket.send("X".encode('utf-8')) # sends "X" to the first client
o_socket.send("O".encode('utf-8')) # sends "O" to the second client

mat_str = mat_to_mat_str(mat) # this function turns the board from matrix into a string so I can send it
ix_socket.send(mat_str.encode('utf-8'))
o_socket.send(mat_str.encode('utf-8'))

row=server_socket.recv(1)

здесь я получаю эту ошибку: "socket.error: [Errno 10057] Запрос на отправку или получение данных был отклонен, поскольку сокет не подключен и (при отправке на сокете дейтаграммы с использованием вызова sendto) адрес не указан "

и программа останавливается ...

col = server_socket.recv(1)
mat[row][col]="X" # should insert row and col received from client X
mat_str=mat_to_mat_str(mat) # should transform the modified board from matrix into string so I can send it
ix_socket.send(mat_str.encode('utf-8')) # should send mat_str to X client
o_socket.send(mat_str.encode('utf-8')) # should send mat_str to O client

Это основной метод в файле клиента:

~~ python

client_socket = socket.socket()
client_socket.connect(("127.0.0.1", 5555))

SIGN = client_socket.recv(1) # receives b"X" or b"O"
SIGN = SIGN.decode('utf-8')

mat_str = client_socket.recv(1024) # receives initial board in byte form
mat_str = mat_str.decode('utf-8') # turns bytes into string
mat = mat_str_to_mat(mat_str) # turns string into matrix (with function)

print("Initial board:")
print_mat(mat) # prints initial board (with no X's nor O's on it)
print("\r")

if SIGN == "X": # if you happend to be the first one to connect you are "X", and you should select a slot - for example 1a - where you want to place an X.
    print("Insert row (1, 2, 3...):")
    row = input()
    print("Insert col (a, b, c...):")
    col = input()
    col = ord(col) - 96
    col=str(col)
    client_socket.send(row.encode('utf-8')) # sending row index
# oops, it is not being received by the server.
# from now on the program doesn't work if you are client X.
    client_socket.send(col.encode('utf-8')) # sending col index

    mat_str=client_socket.recv(1024) # receiving modified board in byte form
    mat_str=mat_str.decode('utf-8') # turning it into string form
    mat_str=mat_str_to_mat(mat_str) # turning it into matrix form

    print("your board now:")
    print_mat(mat) # printing modified board

elif SIGN == "O": # If you happened to be the second one to connect, you are O.
    print("Waiting for X to play.")

    mat_str = client_socket.recv(1024)
# receiving new board in byte form. It doesn't receive anything until client X plays. And he can't play, because the server doesn't receive the row index.
#so the following while loop runs forever:
    while len(mat_str)==0: # waiting until it receives something
        mat_str = client_socket.recv(1024)

    mat_str = mat_str.decode('utf-8') # turning modified board from bytes into string
    mat = mat_str_to_mat(mat_str) # turning string into matrix with function

    print("your board now:")
    print_mat(mat) # printing modified board

1 Ответ

1 голос
/ 07 октября 2019

Из документации на https://docs.python.org/3/library/socket.html#timeouts-and-the-accept-method:

Also note that the server does not sendall()/recv() on the socket it is listening on but on the new socket returned by accept().

Так что server_socket.recv(1) собирается выдать вам ошибку. То, что вы хотите, это то же самое, что и при отправке, при которой используются два соединения.

...