-
Notifications
You must be signed in to change notification settings - Fork 35
/
ClientServer.go
120 lines (98 loc) · 2.44 KB
/
ClientServer.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 (
"fmt"
"net"
"os"
"time"
"github.com/DistributedClocks/GoVector/govec"
)
//Hardcoded client/sever port values, and total messages sent
const (
SERVERPORT = "8080"
CLIENTPORT = "8081"
MESSAGES = 10
)
var done chan int = make(chan int, 2)
func main() {
go server(SERVERPORT)
go client(CLIENTPORT, SERVERPORT)
<-done
<-done
}
func client(listen, send string) {
Logger := govec.InitGoVector("client", "clientlogfile", govec.GetDefaultConfig())
// sending UDP packet to specified address and port
conn := setupConnection(SERVERPORT, CLIENTPORT)
opts := govec.GetDefaultLogOptions()
for i := 0; i < MESSAGES; i++ {
outgoingMessage := i
outBuf := Logger.PrepareSend("Sending message to server", outgoingMessage, opts)
_, errWrite := conn.Write(outBuf)
printErr(errWrite)
var inBuf [512]byte
var incommingMessage int
n, errRead := conn.Read(inBuf[0:])
printErr(errRead)
Logger.UnpackReceive("Received Message from server", inBuf[0:n], &incommingMessage, opts)
fmt.Printf("GOT BACK : %d\n", incommingMessage)
time.Sleep(1)
}
done <- 1
}
func server(listen string) {
Logger := govec.InitGoVector("server", "server", govec.GetDefaultConfig())
fmt.Println("Listening on server....")
conn, err := net.ListenPacket("udp", ":"+listen)
printErr(err)
var buf [512]byte
var n, nMinOne, nMinTwo int
n = 1
nMinTwo = 1
nMinTwo = 1
opts := govec.GetDefaultLogOptions()
for i := 0; i < MESSAGES; i++ {
_, addr, err := conn.ReadFrom(buf[0:])
var incommingMessage int
Logger.UnpackReceive("Received Message From Client", buf[0:], &incommingMessage, opts)
fmt.Printf("Received %d\n", incommingMessage)
printErr(err)
switch incommingMessage {
case 0:
nMinTwo = 0
n = 0
break
case 1:
nMinOne = 0
n = 1
break
default:
nMinTwo = nMinOne
nMinOne = n
n = nMinOne + nMinTwo
break
}
outBuf := Logger.PrepareSend("Replying to client", n, opts)
conn.WriteTo(outBuf, addr)
time.Sleep(1)
}
conn.Close()
done <- 1
}
func setupConnection(sendingPort, listeningPort string) *net.UDPConn {
rAddr, errR := net.ResolveUDPAddr("udp4", ":"+sendingPort)
printErr(errR)
lAddr, errL := net.ResolveUDPAddr("udp4", ":"+listeningPort)
printErr(errL)
conn, errDial := net.DialUDP("udp", lAddr, rAddr)
printErr(errDial)
if (errR == nil) && (errL == nil) && (errDial == nil) {
return conn
}
return nil
}
func printErr(err error) {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}