File: redis-pubsub.tcl

package info (click to toggle)
jimtcl 0.81%2Bdfsg0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 15,416 kB
  • sloc: ansic: 175,569; tcl: 5,456; sh: 4,814; cpp: 1,671; makefile: 269
file content (61 lines) | stat: -rw-r--r-- 1,312 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env jimsh

# Requires the redis extension
package require redis

# A redis server should be running either on localhost 6379
# or on the given host port
#
# Usage: redis-pubsub.tcl ?pub|sub? ?host:addr?
#
# If pub or sub is not given, forks and does both

if {[lindex $argv 0] in {pub sub}} {
    # Run in single process mode
    set argv [lassign $argv op]
} else {
    # fork before connecting so that both processes don't share
    # a connection
    if {[os.fork] == 0} {
        # child subscribes
        set op sub
    } else {
        set op pub
    }
}

try {
    lassign $argv addr
    if {$addr eq ""} {
            set addr localhost:6379
    }
    set r [redis [socket stream $addr]]
} on error msg {
    puts [errorInfo $msg]
    exit 1
}

if {$op eq "sub"} {
    $r SUBSCRIBE chin
    $r SUBSCRIBE chan

    $r readable {
        after cancel $afterid
        set result [$r read]
        puts "$op: $result"
        set afterid [after 2000 {incr done}]
    }
    # If no message for 2 seconds, stop
    set afterid [after 2000 {incr done}]
    vwait done
    puts "$op: quitting on idle"
} else {
    loop i 1 15 {
        $r PUBLISH chan PONG$i
        puts "$op: chan PONG$i"
        after 250
        $r PUBLISH chin PING$i
        puts "$op: chin PING$i"
        after 250
    }
}