I'm trying to send commands to a rasberry pi using a python based socket server, where the server will get various string command, do something and then wait for the next command.
I have a socket server written in python running on a raspberry pi:
import socket
HOST = '' # Symbolic name meaning the local host
PORT = 11113 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error code: ' + str(msg[0]) + 'Error message: ' + msg[1]
sys.exit()
print 'Socket bind complete'
def listen():
s.listen(1)
print 'Socket now listening'
# Accept the connection
(conn, addr) = s.accept()
print 'Server: got connection from client ' + addr[0] + ':' + str(addr[1])
while 1:
data = conn.recv(1024)
tokens = data.split(' ', 1)
command = tokens[0].strip()
print command
# Send reply
conn.send("Ack")
break
conn.close()
# s.close()
listen()
print "connection closed"
listen()
Java Client:
public class Client {
public static void main(String... args) throws Exception {
int portNum = 11113;
Socket socket;
socket = new Socket("192.168.1.20", portNum);
DataOutputStream dout=new DataOutputStream(socket.getOutputStream());
dout.writeUTF("Hello");
dout.flush();
dout.close();
socket.close();
}
}
Python Server starts ok and waits for a connection, when I run the client code the server outputs the hello text followed by a lot of whitespace and then
edit: the white space is that while 1 loop outputing the incoming data and then looping out of control until it crashes. I want to output the text and keep listing for more connections.
edit 2: fixed python so it doesn't crash - i leave the loop and restart the listen process - which works. If this script can be improved please lmk - it doesn't look like it will scale.