我尝试在提示从键盘输入中输入文本后发送数据。代码似乎工作,但提示不会出现。任何人都可以提出原因吗?
要发送的代码是:
#!/usr/bin/python3
import socket
class LogSocket:
def __init__(self, socket):
self.socket = socket
def send(self, data):
print( "Sending {0} to {1}".format(data, self.socket.getpeername()[0]) )
self.socket.send(data)
def close(self):
self.socket.close()
def respond(client):
response = input("Enter a value: ")
client.send(bytes(response, 'utf8'))
client.close()
if __name__ == "__main__":
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost',2401))
server.listen(1)
try:
while True:
client, addr = server.accept()
respond(LogSocket(client))
finally:
server.close()
要接收的代码是:
#!/usr/bin/python3
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 2401))
print("Received: {0}".format(client.recv(1024)))
client.close()
这种行为有点奇怪。当我在发送终端输入“Hello World”然后输入时,当我切换到接收终端并运行接收脚本时,没有输出。当我再次进入“Hello World”并点击输入发件人时,我会重新运行接收脚本并显示“Hello World”,但是输入提示!
发件人输出:
Hello World
Enter a value: Sending b'' to 127.0.0.1
Hello World
Enter a value: Sending b'Hello World' to 127.0.0.1
接收器输出:
$ ./receive_data_socket1.py
Received: b''
$ ./receive_data_socket1.py
Received: b'Hello World'
在Python3中处理套接字经验的人是否可以解释这种行为?我知道行为在3.5中发生了变化,这就是我正在使用的。
答案 0 :(得分:0)
运行服务器时,它会在server.accept()
调用内阻塞,直到连接客户端为止。即,在连接客户端之前,它不会执行下一行代码。它只在下一行respond(...)
函数中触发输入提示。
试试这个
您还可以选择在accept
之前运行输入提示,并将其存储在变量中。然后使用该变量调用respond
- 这是一个代码段
#!/usr/bin/python3
import socket
class LogSocket:
def __init__(self, socket):
self.socket = socket
def send(self, data):
print( "Sending {0} to {1}".format(data, self.socket.getpeername()[0]) )
self.socket.send(data)
def close(self):
self.socket.close()
def respond(client, response):
client.send(bytes(response, 'utf8'))
client.close()
if __name__ == "__main__":
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost',2401))
server.listen(1)
try:
while True:
response = input("Enter a value: ")
client, addr = server.accept()
respond(LogSocket(client), response)
finally:
server.close()