如何使用teln回音

2024-09-28 22:26:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个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()

目前,在我提示“服务器输出:”,它挂起,没有什么是回显到终端。你知道吗


Tags: andtheimport服务器clienthostmessagebind
1条回答
网友
1楼 · 发布于 2024-09-28 22:26:07

问题是在while循环中调用了sockfd.accept()

while True:
   # Establish and accept connections woth client
   (clientsocket, address) = sockfd.accept()

。。。因此,在服务器接收到第一个数据后,它将再次阻塞,等待另一个TCP连接。你知道吗

将该调用移到while True:行上方,您的行为将更符合您的期望。你知道吗

相关问题 更多 >