简体   繁体   中英

Python socket client: send data and receive result

I am trying to develop an application in python that has the following behavior. Knowing the existence of an external socket server , I can currently connect via telnet and have the following result:

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

And the cycle continues... Knowing that everything is working as it should on the server, let's go to the python application. 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).

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:

  1. The welcome message is printed (line 6) as result of the first recv call (line 5);
  2. The application is stuck on line 10 waiting for the server's response...

Solved . The problem was the server was expecting a breakline (\n) to identify a client message...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM