-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
79 lines (62 loc) · 1.48 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 (
"bytes"
"fmt"
"math/rand"
"net"
"os"
"strconv"
"strings"
"sync"
"time"
)
const (
CONN_HOST = "localhost"
CONN_PORT = "8081"
CONN_TYPE = "tcp"
)
var (
stockPrice = make(map[string]float64)
lock = sync.RWMutex{}
)
func quoteHandler(conn net.Conn) {
buffer := make([]byte, 1024)
_, err := conn.Read(buffer)
if err != nil {
fmt.Println(err.Error())
}
commandLength := bytes.Index(buffer, []byte{0})
commandText := string(buffer[:commandLength-1])
commandComponents := strings.Split(commandText, ",")
stock := commandComponents[0]
userId := commandComponents[1]
lock.Lock()
if _, exists := stockPrice[stock]; !exists {
stockPrice[stock] = (rand.Float64() * 1000) + 1
}
lock.Unlock()
responseString := strconv.FormatFloat(stockPrice[stock], 'f', 2, 64) + ","
responseString += stock + "," + userId + ","
responseString += strconv.FormatInt(int64(time.Nanosecond)*int64(time.Now().UnixNano())/int64(time.Millisecond), 10) + ","
responseString += strconv.Itoa(rand.Intn(99999999-10000000) + 10000000)
conn.Write([]byte(responseString))
conn.Close()
}
func main() {
l, err := net.Listen(CONN_TYPE, ":"+CONN_PORT)
if err != nil {
fmt.Println("Cannot listen on port: ", CONN_PORT)
fmt.Println(err.Error())
os.Exit(1)
}
fmt.Println("listening on " + CONN_HOST + ":" + CONN_PORT)
rand.Seed(time.Now().Unix())
for {
conn, err := l.Accept()
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
go quoteHandler(conn)
}
}