-
Notifications
You must be signed in to change notification settings - Fork 21
/
main.go
93 lines (71 loc) · 1.7 KB
/
main.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
package main
import (
"docker_example/proto"
"log"
"net"
"os"
"sync"
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
glog "google.golang.org/grpc/grpclog"
)
var grpcLog glog.LoggerV2
func init() {
grpcLog = glog.NewLoggerV2(os.Stdout, os.Stdout, os.Stdout)
}
type Connection struct {
stream proto.Broadcast_CreateStreamServer
id string
active bool
error chan error
}
type Server struct {
Connection []*Connection
}
func (s *Server) CreateStream(pconn *proto.Connect, stream proto.Broadcast_CreateStreamServer) error {
conn := &Connection{
stream: stream,
id: pconn.User.Id,
active: true,
error: make(chan error),
}
s.Connection = append(s.Connection, conn)
return <-conn.error
}
func (s *Server) BroadcastMessage(ctx context.Context, msg *proto.Message) (*proto.Close, error) {
wait := sync.WaitGroup{}
done := make(chan int)
for _, conn := range s.Connection {
wait.Add(1)
go func(msg *proto.Message, conn *Connection) {
defer wait.Done()
if conn.active {
err := conn.stream.Send(msg)
grpcLog.Info("Sending message to: ", conn.stream)
if err != nil {
grpcLog.Errorf("Error with Stream: %v - Error: %v", conn.stream, err)
conn.active = false
conn.error <- err
}
}
}(msg, conn)
}
go func() {
wait.Wait()
close(done)
}()
<-done
return &proto.Close{}, nil
}
func main() {
var connections []*Connection
server := &Server{connections}
grpcServer := grpc.NewServer()
listener, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatalf("error creating the server %v", err)
}
grpcLog.Info("Starting server at port :8080")
proto.RegisterBroadcastServer(grpcServer, server)
grpcServer.Serve(listener)
}