user ids, per-user logging

master
Jordan Orelli 5 years ago
parent f9cb5adfd8
commit bef1c6210a

@ -12,17 +12,18 @@ func main() {
stdout := blammo.NewLineWriter(os.Stdout)
stderr := blammo.NewLineWriter(os.Stderr)
log := blammo.NewLog("kloam", blammo.DebugWriter(stdout), blammo.InfoWriter(stdout), blammo.ErrorWriter(stderr))
log.Info("this is some info")
log.Info("some more info here")
s := server{
Log: log,
Log: log,
join: make(chan player),
}
s.init()
go s.run()
lis, err := net.Listen("tcp", "0.0.0.0:9001")
if err != nil {
log.Error("listen error: %v", err)
return
}
log.Info("listening on %v", lis.Addr())
http.Serve(lis, s.handler())
}

@ -1,10 +1,70 @@
package main
import "github.com/gorilla/websocket"
import (
"context"
"io/ioutil"
"time"
"github.com/gorilla/websocket"
"github.com/jordanorelli/blammo"
)
type player struct {
*blammo.Log
conn *websocket.Conn
id int
}
func (p *player) readMessages() {
func (p *player) run() {
ctx, cancel := context.WithCancel(context.Background())
p.readMessages(cancel)
go p.writeMessages(ctx)
p.conn.Close()
}
func (p *player) readMessages(cancel func()) {
defer cancel()
for {
_, rd, err := p.conn.NextReader()
if err != nil {
if closeError, ok := err.(*websocket.CloseError); ok {
switch closeError.Code {
case websocket.CloseNormalClosure:
p.Info("client disconnected: %s", closeError.Text)
default:
p.Error("client disconnected weirdly: %#v", *closeError)
}
} else {
p.Error("nextreader error: %s", err)
}
return
}
b, err := ioutil.ReadAll(rd)
if err != nil {
p.Error("read error: %s", err)
} else {
p.Child("rcv").Info(string(b))
}
}
}
func (p *player) writeMessages(ctx context.Context) {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
w, err := p.conn.NextWriter(websocket.TextMessage)
if err != nil {
}
w.Write([]byte("tick"))
w.Close()
case <-ctx.Done():
return
}
}
}

@ -1,8 +1,8 @@
package main
import (
"io/ioutil"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
@ -11,7 +11,9 @@ import (
type server struct {
*blammo.Log
router *mux.Router
router *mux.Router
players map[int]*player
join chan player
}
func (s *server) init() {
@ -33,23 +35,27 @@ func (s *server) play(w http.ResponseWriter, r *http.Request) {
s.Error("upgrade error: %s", err)
return
}
defer conn.Close()
s.Info("client connected: %v", conn.RemoteAddr())
s.join <- player{
conn: conn,
}
}
func (s *server) run() {
s.players = make(map[int]*player)
for {
_, rd, err := conn.NextReader()
if err != nil {
s.Error("nextreader error: %s", err)
break
}
b, err := ioutil.ReadAll(rd)
if err != nil {
s.Error("read error: %s", err)
} else {
s.Child("rcv").Info(string(b))
}
for pc := 0; true; pc++ {
s.step(pc)
}
}
func (s *server) step(pc int) {
select {
case p := <-s.join:
s.Info("received join: %#v", p)
p.id = pc
p.Log = s.Child("players").Child(strconv.Itoa(p.id))
go p.run()
}
}

Loading…
Cancel
Save