Skip to content

Instantly share code, notes, and snippets.

@g14a
Created May 13, 2018 06:45
Show Gist options
  • Save g14a/ab9a87689e03776a07aba2372951a10e to your computer and use it in GitHub Desktop.
Save g14a/ab9a87689e03776a07aba2372951a10e to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"database/sql"
"fmt"
"net"
"strings"
"time"
_ "github.com/go-sql-driver/mysql"
)
func check(err error, message string) {
if err != nil {
panic(err)
}
fmt.Printf("%s", message)
}
type Client struct {
message string
conn net.Conn
}
type Packet struct {
deviceID string
time string
latitude string
longitude string
speed string
angle string
date string
status string
}
func replyResponse(client chan Client) {
for {
individualClient := <-client
for begin := time.Now(); time.Now().Sub(begin) < time.Second; {
}
individualClient.conn.Write([]byte("Your details are " + individualClient.conn.RemoteAddr().String() + "\nHello!, " + individualClient.message))
}
}
func parseAndInsertDB(data string, p *Packet) {
s := strings.Split(data, ",")
p.deviceID = s[1]
p.time = s[3]
p.latitude = s[5]
p.longitude = s[7]
p.speed = s[9]
p.angle = s[10]
p.date = s[11]
p.status = strings.Trim(s[12], "*#")
db, err := sql.Open("mysql", "root:gowtham@/data")
if err != nil {
panic(err.Error())
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err.Error())
}
result, err := db.Exec(`INSERT INTO packetTable (deviceID, time, latitude, longitude, speed, angle, date, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, p.deviceID, p.time, p.latitude, p.longitude, p.speed, p.angle, p.date, p.status)
if err != nil {
println("Exec err:", err.Error())
} else {
id, err := result.LastInsertId()
if err != nil {
println("Error:", err.Error())
} else {
println("LastInsertId:", id)
}
}
}
var count = 0
func main() {
clients := make(chan Client)
go replyResponse(clients)
ln, err := net.Listen("tcp", ":8000")
check(err, "Server is ready\n")
for {
conn, err := ln.Accept()
count++
check(err, "Accepted Connection")
fmt.Printf(" %s\n", conn.RemoteAddr().String())
go func() {
buffer := bufio.NewReader(conn)
for {
message, err := buffer.ReadString('\n')
p := &Packet{}
go parseAndInsertDB(message, p) // tokenizes the data and inserts into the DB
if err != nil {
fmt.Printf("%s disconnected", conn.RemoteAddr().String())
count--
break
} else {
fmt.Printf("%s sent %s", conn.RemoteAddr().String(), message)
}
clients <- Client{message, conn}
}
}()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment