teaching machines

Communication is Key

September 20, 2012 by . Filed under buster.

This past week I was able to get the Raspberry Pi device to communicate with my personal windows computer on my local network, via a simple Python program that I based off of what I found here: http://ilab.cs.byu.edu/python/socket/echoserver.html

I adapted it a little for Python 3.2 and here is what I ended up with:

#client example
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('192.168.1.11', 50000))

while 1:
    data = "0"
    print("While 1")
    if ( data == 'q' or data == 'Q'):
        client_socket.close()
        break;
    else:
        data = input( "SEND( TYPE q or Q to Quit):")
        strData = bytes(data, 'UTF-8')
        if (data != 'Q' and strData != 'q'):
            client_socket.send(strData)
            data = client_socket.recv(1024)
            print ("RECIEVED:" , data)
        else:
            client_socket.send(strData)
            client_socket.close()
            break;
And:
#!/usr/bin/env python
#Server Example
import socket

host = '192.168.1.133'
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()
    print ("Connection!")
    data = client.recv(size)
    print("Got data")
    if data:
        print("Sending data")
        client.send(data)
        print("Sent data")
    client.close()
    print("Closed")

 

I added a lot of print statements so I could trace how the code was running as this was my first experience with the Python language. I didn’t encounter too many snafus making this happen except for changing “raw_input” to “input” and casting it to bytes.

Here is a screenshot of my code after execution: