简体   繁体   中英

One server and 3 clients with using UDP in same time using Python

Good morning. I have recently started learning network and Python programming with using Raspberry Pi (emulator program on Linux) and i have a little problem. My homework is make server and three clients where this clients should get information about temperature from raspberry through server (server sends temperature) in same time (important.) but as I can see this clients get information but it is looks like 1 client get and rest wait until he receive temperature...:and I really don't know what change should I make in my code : (

serwer.py

from sense_emu import SenseHat
from time import sleep
import socket

sense = SenseHat()

UDP_IP = "127.0.0.1"
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

 while 1:
       temp = sense.temp
       tempe = str(temp)
       message = tempe.encode('utf-8')
       sock.sendto(message, (UDP_IP, UDP_PORT))
       sleep(1)

client.py

from time import sleep
import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((UDP_IP, UDP_PORT))

 while 1:
       message, addr = sock.recvfrom(1024)
       mes = str(message)
       print("received message:"+mes)
       sock.close()
       sleep(2)
       sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
       sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
       sock.bind((UDP_IP, UDP_PORT))

I really thought that it should works by bind socket on each client but unfortunately not.

you seem to be misunderstanding how sockets work, I'd suggest going doing some more reading about them

some pointers and general conventions:

  1. normally the "server" process bind s to a specific "well-known" port and clients connect to that address/port
  2. UDP is unreliable (importantly in this case packets can get lost) hence you might need a way of retransmitting values
  3. hosts are unreliable (eg they might be turned off, or change IP address), you might need some way of ensuring the server doesn't send too much data to hosts that might not exist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM