Monday, January 11, 2016

Connect Mac/iPhone to a Simple Python Socket Server (Raspberry Pi Part)

This example shows a simple python socket server on a Raspberry Pi. A custom port is used instead of the HTTP port 80.

The server is tested at a remote Mac computer with:
1) telnet command
2) client python code
3) iOS app on simulator

Setup a socket server

1. Edit the server.py file on Raspberry Pi with this command:

sudo nano server.py

2. Edit and save the file as:

import socket

mysocket = socket.socket()
host = socket.gethostbyname(socket.getfqdn())
port = 9876

if host == "127.0.1.1":
    import commands
    host = commands.getoutput("hostname -I")
print "host = " + host

#Prevent socket.error: [Errno 98] Address already in use
mysocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

mysocket.bind((host, port))

mysocket.listen(5)

c, addr = mysocket.accept()

while True:

    data = c.recv(1024)
    data = data.replace("\r\n", '') #remove new line character
    inputStr = "Received " + data + " from " + addr[0]
    print inputStr
    c.send("Hello from Raspberry Pi!\nYou sent: " + data + "\nfrom: " + addr[0] + "\n")

    if data == "Quit": break

c.send("Server stopped\n")
print "Server stopped"
c.close()

3. Enable the server with this command:

python server.py

Results on a remote Mac computer


1) telnet command

1. Type this command to connect to Raspberry Pi:

telnet 192.168.xx.xx 9876

2. Type these strings:

this is mac
have a nice day
abcdefg
Quit



2) client python code


1. Edit a simple client.py file on Mac as:


import socket

server = socket.socket()
host = "192.168.xx.xx"
port = 9876

server.connect((host, port))
server.sendall("This is client")
print(server.recv(1024)) #Normal server response
server.sendall("Quit")
print(server.recv(1024)) #Quit server response

server.close()

2. Execute the client.py file on Mac terminal:

python client.py




3) iOS app on simulator

Create an iOS app with Swift. See this:
Connect Mac / iPhone to a Simple Python Socket Server (iOS Part)

And the result is:



References:
Connect iOS device to HTTP GET/POST PHP service (Raspberry Pi Part) (iOS Part)
Connect iOS device to MySQL database on a server (Raspberry Pi Part) (iOS Part)
Connect Mac/iPhone to a Simple Python Socket Server (iOS Part)
Sending an RSA encrypted message from client to Python socket server

Go back to Communication between iOS device (Client) and Raspberry Pi (Server)

No comments:

Post a Comment