调用 .recv(1024) 和 .send() 两次,没有任何反应 (Python)

Calling .recv(1024) and .send() twice, nothing happening (Python)

我现在正在尝试学习 Socket 编码,我写了一小段进程到进程通信。 这是服务器代码:

import socket
s = socket.socket()
host = socket.gethostname()
port = 17752
s.bind((host, port))

s.listen(5)
while True:
    (client, address) = s.accept()
    print(address, 'just connected!')
    message = input("Would you like to close the connection? (y/n)")
    if message == 'y':
        message = "False"
        client.send(message.encode(encoding="utf_8"))
        client.close()
        break
    elif message == 'n':
        print("sending message...")
        testing = "Do you want to close the connection?"
        client.send(testing.encode(encoding='utf_8'))
        print("sent!")

和客户端代码:

import socket

client = socket.socket()
host = socket.gethostname()
port = 17752

client.connect((host, port))

while True:
    print("awaiting closing message...")
    closing = client.recv(1024)
    closing = closing.decode(encoding='utf_8')
    print("Closing message recieved and decoded")
    if closing == 'False':
        print("message is false, breaking loop")
        break
    else:
        print("Awaiting message...")
        recieved = client.recv(1024)
        recieved = recieved.decode(encoding='utf_8')
        print("Message recieved and decoded")
        print(recieved)
        sd = input('(y/n) >')
        if sd == 'y':
            print("Closing connection")
            client.close()
            break

print("Sorry, the server closed the connection!")

它的用途是什么?

基本上就是学习和练习套接字编码。 它应该是一个将数据从服务器发送到客户端的程序,两者都能够通过对问题回答 y 或 n 来终止连接。 如果双方都继续回答 n,程序只会保持 运行ning。 一旦有人回答 y,它就会终止服务器或客户端。

现在,我不知道到底哪里出了问题。 如果我为服务器问题 "Would you like to close this connection?" 输入 'y',一切都会正常进行。

如果我键入 'n',服务器会执行它应该执行的操作,但客户端不会收到任何信息。大多数 'print' 语句用于调试。这就是我知道服务器工作正常的方式。

有什么问题吗?我试图找到它,我找不到。

我对 python 和套接字编码有点陌生。所以请放轻松。 谢谢

(我运行它在Win10 cmd下用批处理脚本) (因为它是 Process-to-Process,所以可能不叫 "Server"?)

在您的代码中,每个 connect 都应该在服务器端有一个匹配的 accept
您的客户 connect 每个会话一次, 但是服务器 accepts 在每条消息之后,所以在调用第二个 recv 时,服务器已经在尝试接受另一个客户端。 显然你的服务器应该只处理一个客户端, 所以您可以将对 accept 的调用移出循环:

s.listen(5)
(client, address) = s.accept()
print(address, 'just connected!')

while True:
    message = raw_input("Would you like to close the connection? (y/n)")