socket.send在回显客户端的python代码中仅工作一次 [英] socket.send working only once in python code for an echo client
问题描述
我有一个 echo客户端的以下代码,该代码使用套接字连接将数据发送到 echo服务器:
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.
为什么s.send只工作一次?如何在我的代码中解决此问题?
Why is s.send working only once ?. How can i fix this in my code ?
请帮助 谢谢
推荐答案
您的服务器代码仅调用recv
一次.如果只想接收一个连接,则应该调用一次accept
,但是随后需要循环调用recv
和send
.
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
.
这篇关于socket.send在回显客户端的python代码中仅工作一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!