-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
50 lines (44 loc) · 974 Bytes
/
message.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
package main
import (
"encoding/json"
"net"
)
const (
MESSAGE_CONNECT = "CONNECT"
MESSAGE_DISCONNECT = "DISCONNECT"
MESSAGE_PUBLIC = "PUBLIC"
MESSAGE_SHOW = "SHOW"
)
// Message is a struct that represents a message
type Message struct {
Kind string
Contents string
Author string
}
// CreateMessage creates a new message
func CreateMessage(kind string, contents string, author string) *Message {
return &Message{
Kind: kind,
Contents: contents,
Author: author,
}
}
// Send sends the message to all the connections
func (this *Message) Send(peers map[string]net.Conn) error {
for name, conn := range peers {
if name != this.Author {
if err := this.SendTo(conn); err != nil {
return err
}
}
}
return nil
}
// SendTo sends the message to a specific connection
func (this *Message) SendTo(conn net.Conn) error {
enc := json.NewEncoder(conn)
if err := enc.Encode(this); err != nil {
return err
}
return nil
}