简体   繁体   中英

socket.send working only once in python code for an echo client

I have the following code for an echo client that sends data to an echo server using 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 facing is that in the client s.send works only the first time even though its in an infinite loop. The client crashes with connection timed out, some time after the first send/receive has completed .

Why is s.send working only once ?. How can i fix this in my code ?

Please Help Thank You

Your server code only calls recv once. You should call accept once if you only want to receive one connection, but then you need to loop calling recv and send .

Your problem is that you are blocking on the accept inside the server's loop.

This is expecting the server to accept connections from more than one client. If you want that, and for each client to send multiple commands, you would need to spawn a new thread (or process) after the accept, with a new while loop (for client communication) in that thread/process.

To fix your example to work with just one client, you need to move the accept outside the loop, like so:

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

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