ich bin schon eine Weile damit beschäftigt eine Netzwerkverbindung zwischen meinem Raspberry und meine PC aufzubauen.
Leider funktioniert das nicht so wie ich es will. Auf meinem Rechner starte ich den ThreadedServer und auf dem Pi den Client, der dann "Hallo Welt" senden soll.
Beide Geräte können sich gegenseitig anpingen aber, der Client stoppt bei sock.connect() schmeißt dann den timeout. Der Host wartet konstant auf eine Meldung des Clients bei sock.accept(). Das locale Netzwerk habe ich mit einem TPLinkWifi aufgebaut und den Port 1101 als Virtual Server geöffnet (auf jeden glaube ich das).
Habt ihr einen Tip für mich?
Code: Alles auswählen
import socket
import threading
from time import *
class ThreadedServer(object):
def __init__(self, host=socket.gethostname(), port=1101):
if host is None:
self.host = socket.gethostname()
else:
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
def listen(self):
self.sock.listen(5)
while True:
print("Waiting for client...")
client, address = self.sock.accept()
print ("Client %s gefunden mit der Adresse %s\n") % (client, adress)
client.settimeout(60)
threading.Thread(target=self.listenToClient, args=(client, address)).start()
def listenToClient(self, client, address):
print("Listener aktiviert fuer Server: %s\n") % socket.gethostname()
size = 1024
while True:
try:
data = client.recv(size)
print(data)
# if data:
# Todo: Daten handeln
# response = data
# client.send(response)
# else:
# raise Exception('Client disconnected')
except:
client.close()
return False
class Client(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("Try to connect...")
try:
self.sock.connect((host, port))
except socket.gaierror, e:
print "Address-related error connecting to server: %s" % e
sys.exit(1)
except socket.error, e:
print "Connection error: %s" % e
sys.exit(1)
print "Connected to %s" % host
def connect(self, host, port):
self.sock.connect((host, port))
def send(self, data):
totalsent = 0
while totalsent < len(data):
sent = self.sock.send(data[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
if __name__ == "__main__":
modus = "host"
if modus == "host":
ThreadedServer().listen()
elif modus == "client":
c = Client('192.168.0.100', 1101)
while True:
c.send("Hello World!")
print("Daten gesendet")
sleep(1)