Skip to content

Instantly share code, notes, and snippets.

@pjambet
Created April 19, 2021 16:38
Show Gist options
  • Save pjambet/8b11cbb95fa756921f5aaa23f5ff54db to your computer and use it in GitHub Desktop.
Save pjambet/8b11cbb95fa756921f5aaa23f5ff54db to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
// "sync/atomic"
"bufio"
"net"
// "strconv"
"strings"
"time"
// "random"
)
type readMessageOp struct {
key string
resp chan string
}
type writeMessageOp struct {
key string
value string
resp chan bool
}
const MIN = 1
const MAX = 100
func random() int {
return rand.Intn(MAX-MIN) + MIN
}
func handleConnection(c net.Conn, reads chan readMessageOp, writes chan writeMessageOp) {
fmt.Printf("Serving %s\n", c.RemoteAddr().String())
for {
netData, err := bufio.NewReader(c).ReadString('\n')
if err != nil {
fmt.Println(err)
fmt.Println("Closing!")
c.Close()
return
}
var response string
temp := strings.TrimSpace(string(netData))
if temp == "STOP" {
break
} else if temp == "GET" {
op := readMessageOp{
key: c.RemoteAddr().String(),
resp: make(chan string),
}
reads <- op
response = <-op.resp
} else if strings.HasPrefix(temp, "SET") {
value := strings.Split(temp, " ")[1]
op := writeMessageOp{
key: c.RemoteAddr().String(),
value: value,
resp: make(chan bool),
}
writes <- op
fmt.Println(<-op.resp)
response = value
} else {
response = "N/A"
}
c.Write([]byte(response + "\n"))
}
fmt.Println("Closing!")
c.Close()
}
func main() {
// var readOps uint64
// var writeOps uint64
state := make(map[string]string)
readMessages := make(chan readMessageOp)
writeMessages := make(chan writeMessageOp)
go func() {
for {
select {
case message := <-readMessages:
var res string
if val, ok := state[message.key]; ok {
res = val
} else {
res = "Nil"
}
fmt.Println(state)
message.resp <- res
close(message.resp)
case message := <-writeMessages:
state[message.key] = message.value
message.resp <- true
}
}
}()
PORT := ":" + "2000"
l, err := net.Listen("tcp4", PORT)
if err != nil {
fmt.Println(err)
return
}
defer l.Close()
rand.Seed(time.Now().Unix())
for {
c, err := l.Accept()
if err != nil {
fmt.Println(err)
return
}
go handleConnection(c, readMessages, writeMessages)
}
// time.Sleep(time.Second)
// readOpsFinal := atomic.LoadUint64(&readOps)
// fmt.Println("readOps:", readOpsFinal)
// writeOpsFinal := atomic.LoadUint64(&writeOps)
// fmt.Println("writeOps:", writeOpsFinal)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment