I'd like to set up a system where I have a python client and server continuously sending / receiving data. All of the code examples I've found show how to send a single message to a socket, but not how to continuously be set up for sending/receiving data.
Right now my code is:
client.py
import socket
import time
while True:
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("192.168.0.250", 10220))
data = "GET\nSONAR\n\n"
print 'send to server: ' + data
client_socket.send(data)
client_socket.close()
except Exception as msg:
print msg
I'd like the code to be able to send commands multiple times a minute, but right now it doesn't seem to consistently send messages out, and i'm not sure why. Why isn't the control stream continuous?
server.py
import socket
host = '192.168.0.100'
port = 8220
address = (host, port)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((address))
server_socket.listen(5)
while True:
try:
print "Listening for client . . ."
conn, address = server_socket.accept()
print "Connected to client at ", address
#pick a large output buffer size because i dont necessarily know how big the incoming packet is
output = conn.recv(2048);
if output:
print "Message received from client:"
print output
#conn.send("This is a response from the server.")
conn.close()
#print "Test message sent and connection closed."
This works fine on the first try, but I can't have the server automatically listen again for the next message -- it always hangs on "Listening for client . . .".
Any thoughts?
thanks!