Jump to content

Sending data with sockets but continusly (betwin Raspi and PC)

so i want to send data like sensor data over local network and i have been sucsesful to sending a text but i cant send ot continusly

Pc code (master):

# Echo server program
import socket
import time
#HOST = ''                 # Symbolic name meaning all available interfaces


PORT = 50007              # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind(('', PORT))
    s.listen(1)
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            print(data)
            #time.sleep(1)
            #conn.sendall(bytes("Hello Slave!!", encoding='utf8'))
            conn.sendall(b'Hello Slave!!')
            #if not data: break
            #conn.sendall(data)

Raspi code(slave):

# Echo client program
import time
import socket

HOST = 'Ip of pc'    # The remote host
PORT = 50007              # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    
    data = s.recv(1024)
while True:
    s.sendall(b'Hello, world')
    print('Received', repr(data))
    #time.sleep(1)

 

Link to comment
Share on other sites

Link to post
Share on other sites

You're using the with statement outside of your loop meaning that your socket will be closed when you exit that code (aka your indentation is wrong). You're also in effect receiving data on the client once, but sending it in a loop from your server. You do not need to send data back to the client by the look of it, unless you do in your use case

 

Server loop should look something like:

while true:

    data = connection.receive()

    if not data:

        break

    processData(data)

 

Client loop should look something like:

while true:

    data = getSensorData()

    socket.sendall(data)

    time.sleep(1)

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×