使用线程时聆听特定数据

时间:2014-12-14 23:47:49

标签: python multithreading sockets

我正在尝试在端口上侦听正在传输的特定消息以停止我的程序。

以下是使用sockets收听的功能:

def receive():
    host = ""
    port = 13000
    buf = 1024
    addr = (host,port)
    Sock = socket(AF_INET, SOCK_DGRAM)
    Sock.bind(addr)
    (data, addr) = Sock.recvfrom(buf)
    return data

我已让它在后台运行threading

while True:
    r = threading.Thread(target=receive)
    r.start()
    if r == "stop":
        print "Stopped"
        break
    print "Running program"

r = threading 内的如上时,我得到:

error: [Errno 98] Address already in use

当我在while循环之外定义r = threading (在它之前)时,我得到:

RuntimeError: threads can only be started once

我试过这个,但是当我发送“stop”命令时它发送线程RuntimeError 并退出程序:

if r.is_alive == False:
    r.start()

1 个答案:

答案 0 :(得分:0)

如果你坚持使用线程:

CassCluster* cluster = cass_cluster_new();
CassSession* session = cass_session_new();
const char* hosts    = "192.168.57.101";
cass_cluster_set_contact_points(cluster, hosts);
cass_cluster_set_blacklist_filtering(cluster, hosts);
CassFuture* connect_future = cass_session_connect(session, cluster);