-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
79 lines (61 loc) · 1.62 KB
/
server.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
package main
import (
"io"
"log"
"net"
"sync"
pb "github.com/Kethsar/clipboardsync/clipboard_proto"
"google.golang.org/grpc"
)
type csServer struct{}
var clients map[pb.ClipboardSync_SyncServer]bool
var smux sync.Mutex
func (css *csServer) Sync(stream pb.ClipboardSync_SyncServer) error {
printToConsole("Server: Client connected")
clients[stream] = true
if cboard != "" { // Send the currently stored clipboard, if it exists
stream.Send(&pb.Clipboard{Data: cboard})
}
// Loop and attempt to read new data from the client
for {
in, err := stream.Recv()
if err != nil {
printToConsole("Server: Client disconnected")
// Remove the client from our list of clients, since we lost them
smux.Lock()
delete(clients, stream)
smux.Unlock()
if err != io.EOF {
return err
}
return nil
}
// Send clipboard out only if it is different
if setClipboard(in.GetData()) {
printToConsole("Server: New clipboard received")
propagate(cboard, stream)
}
}
}
// Send the specified text to all connected clients, except the one that sent it to the server
func propagate(text string, source pb.ClipboardSync_SyncServer) {
smux.Lock()
defer smux.Unlock()
for stream := range clients {
if stream != source {
stream.Send(&pb.Clipboard{Data: text})
}
}
}
func startServer() {
lis, err := net.Listen("tcp", c.Port)
if err != nil {
log.Fatalf("Failed to listen: %v\n", err)
}
clients = make(map[pb.ClipboardSync_SyncServer]bool)
s := grpc.NewServer()
pb.RegisterClipboardSyncServer(s, &csServer{})
if err := s.Serve(lis); err != nil {
log.Fatalf("Error while serving: %v\n", err)
}
}