Socket.send only works once in python code for echo client

I have the following code for an echo client that sends data to an echo server using a socket connection:

echo_client.py

import socket host = '192.168.2.2' port = 50000 size = 1024 def get_command(): #..Code for this here s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) while 1: msg = get_command() if msg == 'turn on': s.send('Y') elif msg == 'turn off': s.send('N') elif msg == 'bye bye': break else: s.send('X') data = s.recv(size) print 'Received: ',data s.close() 

echo_server.py

 import socket host = '' port = 50000 backlog = 5 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(backlog) while 1: client, address = s.accept() data = client.recv(size) if data: client.send(data) client.close() 

The problem im encounters is that the client s.send only works for the first time , although its in an infinite loop. The client departs with the expiration of time , some time after the completion of the first sending / receiving .

Why does s.send work only once ?. How can I fix this in my code?

Please help. Thank you.

+4
source share
2 answers

Server code only calls recv once. You must call accept once if you want to receive only one connection, but then you need to call recv and send .

+5
source

Your problem is that you block accept inside the server loop.

The server is expected to accept connections from multiple clients. If you want this and send several commands for each client, you will need to create a new thread (or process) after acceptance, with a new while loop (to communicate with the client) in this thread / process.

To fix your example for working with one client, you need to move accept outside the loop, for example:

 client, address = s.accept() while 1: data = client.recv(size) if data: client.send(data) 
+1
source

Source: https://habr.com/ru/post/1384190/


All Articles