-
Notifications
You must be signed in to change notification settings - Fork 12
/
broadcast.go
120 lines (100 loc) · 2.49 KB
/
broadcast.go
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package main
import (
"bytes"
"encoding/gob"
"encoding/json"
"io/ioutil"
"log"
"net"
"os"
"sync"
"time"
"github.com/gautamrege/gochat/api"
)
//Edit: Local Network broadcast address
const broadcastAddress = "192.168.1.255:33333"
// Broadcast Listener , Listens on 33333 and updates the Global Users list
func listenAndRegisterUsers(wg *sync.WaitGroup) {
defer wg.Done()
var user api.Handle
for {
// startServer to port 33333
udpAddress, _ := net.ResolveUDPAddr("udp4", broadcastAddress)
udpConn, err := net.ListenUDP("udp", udpAddress)
if err != nil {
log.Print(err)
}
// read the data and add to users.
inputBytes := make([]byte, 4096)
length, _, _ := udpConn.ReadFromUDP(inputBytes)
buffer := bytes.NewBuffer(inputBytes[:length])
decoder := gob.NewDecoder(buffer)
decoder.Decode(&user)
// Ignore the user with same host
if user.Host != MyHandle.Host {
USERS.Insert(user)
}
udpConn.Close()
}
}
// broadcastOwnHandle go-routine that publishes it's Handle on 33333
func broadcastOwnHandle(wg *sync.WaitGroup) {
defer wg.Done()
// Broadcast immediately at the start
broadcastIsAlive()
ticker := time.NewTicker(time.Second * 10)
defer ticker.Stop()
for {
select {
case <-ticker.C:
broadcastIsAlive()
}
}
}
// broadcast on 33333 every 10 seconds with MyHandle(own) Handler
func broadcastIsAlive() {
conn, err := net.Dial("udp", broadcastAddress)
defer conn.Close()
if err != nil {
log.Print(err)
return
}
var buffer bytes.Buffer
encoder := gob.NewEncoder(&buffer)
encoder.Encode(MyHandle)
conn.Write(buffer.Bytes())
buffer.Reset()
}
func preloadUsers() error {
jsonFile, err := os.Open("users.json")
// if we os.Open returns an error then handle it
if err != nil {
log.Print(err)
return err
}
log.Print("Successfully Opened users.json")
// defer the closing of our jsonFile so that we can parse it later on
defer jsonFile.Close()
// read our opened xmlFile as a byte array.
byteValue, err := ioutil.ReadAll(jsonFile)
if err != nil {
log.Print(err)
return err
}
// we unmarshal our byteArray which contains our
// jsonFile's content into 'users' which we defined above
var users []api.Handle
err = json.Unmarshal(byteValue, &users)
if err != nil {
log.Print(err)
return err
}
// we iterate through every user within our users array and
// print out the user Type, their name, and their facebook url
// as just an example
for _, u := range users {
USERS.Insert(u)
log.Printf("User %s added", u.Name)
}
return nil
}