Last active
February 18, 2018 14:37
-
-
Save jaxlo/aee76143d519c41060921c4de8187f18 to your computer and use it in GitHub Desktop.
Posted on reddit to get help with python socket programming -- (This includes the server and client in one file)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
NetworkPort = 59281 | |
class NetworkClient:#run on ML /remote computer | |
#global NetworkHost, NetworkPort | |
def __init__(self, sock=None): | |
if sock is None: | |
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
else: | |
self.sock = sock | |
def connect(self, host=NetworkHost, port=NetworkHost):#put in init? | |
self.sock.connect((NetworkHost, NetworkPort)) | |
print('Connected to: '+NetworkHost+ ' On port: '+str(NetworkPort)) | |
def send(self, msg):#used for sending orders | |
self.sock.sendall(msg.encode())#sendall only stops sending when everything is sent | |
def listen(self):#used for getting images | |
final = ''#try the "final += data" trick if it errors | |
while True: | |
data = self.sock.recv(1024) | |
data = data.decode() | |
if data != '':#if something was received | |
print('something was found') | |
return data#only exit for the loop/ function | |
net = NetworkClient()#this works | |
net.connect()#this works | |
net.send(str('order'))#this works | |
image = net.listen()#broken(see reddit for why) | |
print('image: '+str(image)) | |
#End of client program | |
import socket | |
NetworkPort = 59281 | |
class NetworkServer:#run on the pi | |
#global NetworkHost, NetworkPort | |
def __init__(self, sock=None, port=NetworkPort): | |
if sock is None: | |
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
self.sock.bind(('', NetworkPort))#allow any ip | |
self.sock.listen(1)#limit connection to one client | |
print('Waiting for the ML client') | |
self.conn, addr = self.sock.accept() | |
print('New connection from: [add later]') | |
else: | |
self.sock = sock | |
def send(self, msg): | |
self.sock.sendall(msg.encode()) | |
def listen(self): | |
while True: | |
data = self.conn.recv(1024) | |
data = data.decode() | |
if data != '':#if something was received | |
return data#only exit of the loop/ function | |
net = NetworkServer()#this works | |
array = net.listen()#this works | |
print('array: '+array)#this works | |
net.send('sml')#broken(see reddit for why) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment