【问题标题】:Python socket client: send data and receive resultPython套接字客户端:发送数据和接收结果
【发布时间】:2021-06-25 14:45:28
【问题描述】:

我正在尝试在 python 中开发一个具有以下行为的应用程序。知道外部套接字服务器的存在,我目前可以通过 telnet 进行连接,结果如下:

telnet localhost 1234

当我连接到服务器时,会返回一条消息给我,例如:

欢迎

已经连接,我可以发送一些命令,并且对于每个命令我都有响应:

current-time

当我发送命令 current-time 服务器返回:

2021-03-29 11:38:55

然后循环继续......知道一切都在服务器上正常运行,让我们转到 python 应用程序。下面是我尝试的代码,我想知道我哪里出错了,因为我无法复制提到的操作(通过 telnet)。

1.  client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2.
3.  client.connect(("localhost", 1234))
4. 
5.  welcome_response = client.recv(4096)
6.  print(welcome_response)
7.
8.  client.send('current-time'.encode())
9.
10. command_response = client.recv(4096)
11. print(command_response)

评论:

  1. welcome 消息作为第一次 recv 调用(第 5 行)的结果打印(第 6 行);
  2. 应用程序卡在第 10 行等待服务器响应...

【问题讨论】:

  • 服务器是否在 Python 中工作?你能分享它以便我们重现吗?
  • 不,不是。而且我无权访问代码,只有文档(命令和响应)......

标签: python python-3.x sockets telnet python-sockets


【解决方案1】:

已解决。问题是服务器期望 breakline (\n) 来识别客户端消息...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2016-12-16
    • 2021-11-09
    • 2020-07-10
    • 2017-09-30
    • 1970-01-01
    相关资源
    最近更新 更多