我创建了一个echo服务器,它侦听传入的连接并回显任何接收到的数据。我正在使用telnet建立连接。你知道吗
#!/usr/bin/env python
import socket
import sys
# Create socket
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Port for socket and Host
PORT = 8001
HOST = 'localhost'
# bind the socket to host and port
sockfd.bind((HOST, PORT))
# become a server socket
sockfd.listen(5)
while True:
# Establish and accept connections woth client
(clientsocket, address) = sockfd.accept()
print("Got connection from", address)
# Recieve message from the client
message = clientsocket.recv(1024)
reply = 'Server output: ' + message.decode('utf-8')
if not message:
break
# Display messags.
clientsocket.sendall(str.encode(reply))
# Close the connection with the client
clientsocket.close()
目前,在我提示“服务器输出:”,它挂起,没有什么是回显到终端。你知道吗
问题是在while循环中调用了
sockfd.accept()
:。。。因此,在服务器接收到第一个数据后,它将再次阻塞,等待另一个TCP连接。你知道吗
将该调用移到
while True:
行上方,您的行为将更符合您的期望。你知道吗相关问题 更多 >
编程相关推荐