Batteriesnotincluded
Posts: 7
Joined: Fri Apr 04, 2014 12:34 pm

Raspberry pi sockets

Mon Apr 21, 2014 1:14 pm

Hi
We are trying to control a robot with two RPis using sockets. We have a control programme in python than will need to be split up into two parts for a transmit part and a receive part. Can anybody help on what is required for using sockets, how to use sockets, and the best way to split the programme up?
Many thanks

User avatar
FLYFISH TECHNOLOGIES
Posts: 1750
Joined: Thu Oct 03, 2013 7:48 am
Location: Ljubljana, Slovenia
Contact: Website

Re: Raspberry pi sockets

Mon Apr 21, 2014 1:25 pm

Hi,
Batteriesnotincluded wrote:Can anybody help
General question leads to general answer:
https://docs.python.org/2/howto/sockets.html
http://ilab.cs.byu.edu/python/socket/echoserver.html
http://ilab.cs.byu.edu/python/socket/echoclient.html


Best wishes, Ivan Zilic.
Running out of GPIO pins and/or need to read analog values?
Solution: http://www.flyfish-tech.com/FF32

User avatar
DougieLawson
Posts: 39602
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: Raspberry pi sockets

Mon Apr 21, 2014 1:56 pm

BTW, programme is to TV as program is to computing.

/pi/python/SimpleServer.py

Code: Select all

import socket
import threading
class SimpleServer:
  def __init__(self, host, port):
    self.host = host
    self.port = port
    self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.sock.settimeout(None)
    self.client_sockets = []

  def initialise(self):
    try:
      self.sock.bind((self.host, self.port))
    except socket.error:
      return
    self.sock.listen(5)
    self.server_thread = threading. Thread(target=self. serve_forever)
    self.server_thread.setDaemon(True)
    self.server_thread.start()
    print "Server running on %s and listening on %d" % (self.host, self.port)

  def serve_forever(self):
    try:
      request, client_address = self.sock.accept()
    except socket.error:
      return
    self.client_sockets.append(request)
    print "Received connection from " , client_address
    request.send("Hello caller")
/home/pi/python/ss.py

Code: Select all

#!/usr/bin/python

from SimpleServer import SimpleServer
import socket
server = SimpleServer("192.168.1.7", 20000)  # <=== change me 
server.initialise()
server.serve_forever()
/home/pi/python/sc.py

Code: Select all

#!/usr/bin/python

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("192.168.1.7",20000)) # The IP of the server machine <=== change me
msg = sock.recv(1024)
print msg
sock.close()
Start ss.py with
python ss.py &
connect to it with
python sc.py
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All fake doctors are on my foes list.

Return to “Networking and servers”