简体   繁体   中英

Python UDP communication using Socket, check data received

I'm pretty new to the Python, trying to write a code to receive string from UDP connection, the problem I have now is that I need to receive data from 2 sources, I want the program continue looping if there is no data from either or both of them, but now if there is no data from source 2, it will stop there and wait for the data, how to solve it? I was thinking about using if statement, but I don't know how to check if the incoming data is empty of not, any ideas will be appreciated!

import socket

UDP_IP1 = socket.gethostname()
UDP_PORT1 = 48901
UDP_IP2 = socket.gethostname()
UDP_PORT2 = 48902

sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock1.bind((UDP_IP1, UDP_PORT1))
sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock2.bind((UDP_IP2, UDP_PORT2))

while True:
    if sock1.recv != None:
        data1, addr = sock1.recvfrom(1024)
        data1_int = int(data1)
        print "SensorTag[1] RSSI:", data1_int

    if sock2.recv != None:
        data2, addr = sock2.recvfrom(1024)
        data2_int = int(data2)
        print "SensorTag[2] RSSI:", data2_int

If select doesn't work out for you you can always throw them into a thread. You'll just have to be careful about the shared data and place good mutex around them. Seethreading.Lock for help there.

import socket
import threading
import time

UDP_IP1 = socket.gethostname()
UDP_PORT1 = 48901
UDP_IP2 = socket.gethostname()
UDP_PORT2 = 48902

sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock1.bind((UDP_IP1, UDP_PORT1))
sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock2.bind((UDP_IP2, UDP_PORT2))

def monitor_socket(name, sock):
    while True:
        sock.recv is not None:
            data, addr = sock.recvfrom(1024)
            data_int = int(data)
            print(name, data_int)
    
t1 = threading.Thread(target=monitor_socket, args=["SensorTag[1] RSSI:", sock1
t1.daemon = True
t1.start()
    
t2 = threading.Thread(target=monitor_socket, args=["SensorTag[2] RSSI:", sock2])
t2.daemon = True
t2.start()
    
while True:
    #  We don't want to while 1 the entire time we're waiting on other threads
    time.sleep(1)

Note this wasn't tested due not having two UPD sources running.

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