How to send integers from the client to the server.Python socket
Who rummages in the client-server in python, the socket library help to solve the problem please.
SERVER TASK:
- Create a server that receives a number, multiplies it by 10, and sends it back to the client.
- When the "stop" command is received, the server must be stopped (in the example from the lesson, this can be done by completing an infinite loop using break).
CLIENT TASK:
- Create a client that sends the server from the previous exercise is the number 5, then another number 10, and then the "stop" command.
- Make sure that everything works correctly, that is, the server should send "50" after the first command, "100" after the second, and after the "stop" command should be stopped (that is, the program from the previous exercise should stop).
SERVER CODE
import socket
SERVER_ADDRESS = ('', 15253)
server = socket.socket()
server.bind(SERVER_ADDRESS)
server.listen(1)
print("Ждём подключения клиента...")
while True:
c, a = server.accept()
data = c.recv(4096)
b = data.decode("UTF-8")
print("Получили от клиента:", b)
if b == 'stop':
print("Заверешение")
break
data = data * 10
c.send(data)
c.close()
CLIENT CODE
import socket
SERVER_ADDRESS = ('localhost', 15253)
client = socket.socket()
client.connect(SERVER_ADDRESS)
client.send(bytes("5", encoding="UTF-8"))
data = client.recv(4096)
print(data.decode("UTF-8"))
The problem is that I do not know how to convert a string to a number in this topic because there the reading goes to bytes. When the client server starts, 10 fives are returned With the "stop" command, everything worked out .
0
1 answers
Your server is easier to fix like this:
break
data=bytes(str(int(data) *10), "ascii" )
c.send(data)
But I would recommend using some sort of transfer protocol for more complex tasks. For example, implement TLV:
Server
INT=1
STOPSERVER=2
END=3
accepting = True
while accepting:
c, a = server.accept()
while True:
data = c.recv(2)
type, length = data
if length:
data = c.recv(length)
if type == END:
break
if type == STOPSERVER:
accepting = False
break
if type == INT:
data = int.from_bytes(data,"big")
data *= 10
c.send(bytes[INT,4])
c.send(data.to_bytes(4,'big'))
c.close()
Client
client.send(bytes[INT,4])
client.send((5).to_bytes(4,'big'))
client.send(bytes[END,0])
1
Author: eri, 2020-07-19 09:03:09