forked from HackToHell/bustracker
/
server.go
103 lines (89 loc) · 2.5 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// server
package main
import (
"code.google.com/p/goprotobuf/proto"
"database/sql"
"fmt"
_ "github.com/lib/pq"
"msgproto"
"net"
"os"
// "strconv"
)
const (
CONN_HOST = "192.168.1.101"
CONN_PORT = "8090"
CONN_TYPE = "tcp"
)
//func createdatabd(n int) {
// db, err := sql.Open("postgres", "user=postgres password='pol' dbname=test sslmode=disable ")
// var doesitexist string
// if err != nil {
// fmt.Println(err)
// }
// for i := 0; i <= n; i++ {
// rows, err := db.Exec("SELECT EXISTS(SELECT * FROM information_schema.tables WHERE table_name=$1)", n).Scan(&doesitexist)
// fmt.Println(rows)
// if err != nil {
// fmt.Println(err)
// }
// if doesitexist == "t" {
// } else {
// rows, err := db.Exec("CREATE TABLE $1(Lat numberic(10),Long numeric(10),utime timestamp", n)
// if err != nil {
// fmt.Println(err)
// }
// }
// }
//}
func handleRequest(conn net.Conn) {
data := make([]byte, 4096)
// Read the incoming connection into the buffer.
n, err := conn.Read(data)
if err != nil {
fmt.Println("Error reading:", err.Error())
}
protodata := new(msgproto.Msg)
err = proto.Unmarshal(data[0:n], protodata)
fmt.Println(protodata.GetId())
fmt.Println(protodata.GetLat())
// Close the connection when you're done with it.
conn.Close()
//go writedata(protodata)
}
func writedata(ProtoMessage *msgproto.Msg) {
db, err := sql.Open("postgres", "user=postgres password='pol' dbname=test sslmode=disable ")
if err != nil {
fmt.Println(err)
}
//var query string
//string = "INSERT INTO bus_" + string(ProtoMessage.GetId()) + " values(" + strconv.FormatInt(ProtoMessage.GetLat(), 10) + "," + strconv.FormatInt(ProtoMessage.GetLong(), 10) + "," + strconv.FormatInt(ProtoMessage.GetUtime(), 10)
rows, err := db.Exec("INSERT INTO $1 values($2,$3,to_timestamp($4))", ProtoMessage.GetId(), ProtoMessage.GetLat(), ProtoMessage.GetLong(), ProtoMessage.GetUtime())
if err != nil {
fmt.Println(err)
}
fmt.Println(rows)
}
func main() {
//createdatabd(10)
l, err := net.Listen(CONN_TYPE, ":"+CONN_PORT)
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
fmt.Println("Hi")
// Close the listener when the application closes.
defer l.Close()
for {
// Listen for an incoming connection.
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
os.Exit(1)
}
//logs an incoming message
fmt.Printf("Received message %s -> %s \n", conn.RemoteAddr(), conn.LocalAddr())
// Handle connections in a new goroutine.
go handleRequest(conn)
}
}