[英]Python socket client: send data and receive result
I am trying to develop an application in python that has the following behavior.我正在尝试在 python 中开发具有以下行为的应用程序。 Knowing the existence of an external socket server , I can currently connect via telnet and have the following result:
知道外部套接字服务器的存在,我目前可以通过 telnet 连接并得到以下结果:
telnet localhost 1234
When I connect to the server, a message is returned to me, ex:当我连接到服务器时,会向我返回一条消息,例如:
welcome
欢迎
Already connected I can send some commands and for each command I have a response:已经连接,我可以发送一些命令,并且对于每个命令我都有一个响应:
current-time
When I send the command current-time the server returns:当我发送命令当前时间服务器返回:
2021-03-29 11:38:55
2021-03-29 11:38:55
And the cycle continues... Knowing that everything is working as it should on the server, let's go to the python application.并且循环继续......知道一切都在服务器上正常工作,让我们从 go 到 python 应用程序。 Below is the code of my attempt and I would like to know where I am going wrong since I cannot replicate the mentioned operation (via telnet).
下面是我尝试的代码,我想知道我哪里出错了,因为我无法复制提到的操作(通过 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)
Comments:注释:
Solved .解决了。 The problem was the server was expecting a breakline (\n) to identify a client message...
问题是服务器期待一个断线(\n) 来识别客户端消息......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.