【问题标题】:How to echo using telnet如何使用 telnet 回显
【发布时间】:2019-01-10 15:12:19
【问题描述】:

我创建了一个回显服务器,用于侦听传入连接并回显任何接收到的数据。我正在使用 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()

目前在我提示“服务器输出:”后,它挂起并且没有任何内容回显到终端。

【问题讨论】:

    标签: python sockets


    【解决方案1】:

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

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

    ...因此,服务器收到第一个数据后,会再次阻塞,等待另一个TCP连接。

    将该调用移至while True: 行上方,您将获得更符合您期望的行为。

    【讨论】:

    • 另一个快速的问题。在这种情况下是否需要 decode() 和 encode() 。我在做一些研究时看到了它,但从未完全理解这个人。我可以简单地使用 clientsocket.sendall(message) 并获得相同的行为吗?
    • 也很有趣,它似乎没有回显消息。它在每个字符之后创建一个新的连接。我一个字都打不出来。
    • 听起来您的 telnet 客户端设置为字符模式而不是行模式,并且您还没有将 accept() 调用移出循环?
    猜你喜欢
    • 2013-06-17
    • 2018-09-30
    • 2012-03-01
    • 2011-05-08
    • 2016-12-31
    • 2013-12-19
    • 2019-10-12
    • 2012-03-19
    • 2014-11-28
    相关资源
    最近更新 更多