~sircmpwn/cells

4b4743b3a10220546f06f9964ef8a7a867bca9f0 — Drew DeVault a month ago a0c7f20
Fix races with websocket handling
2 files changed, 26 insertions(+), 9 deletions(-)

M conn.go
M index.js
M conn.go => conn.go +25 -9
@@ 16,15 16,31 @@ var (
)

type Connection struct {
	Conn   *websocket.Conn
	Player Player
	Conn     *websocket.Conn
	Player   Player
	outgoing chan interface{}
}

func (c *Connection) Send(msg interface{}) {
	c.outgoing <-msg
}

func (c *Connection) Run() {
	conns.Store(c, nil)
	c.Player.Id = atomic.AddInt64(&nextId, 1)
	c.outgoing = make(chan interface{})

	go func() {
		for {
			msg := <-c.outgoing
			if msg == nil {
				break
			}
			c.Conn.WriteJSON(msg)
		}
	}()

	c.Conn.WriteJSON(&SpawnSelfMessage{
	c.Send(&SpawnSelfMessage{
		Message: Message{"spawn_self"},
		Self:    c.Player,
	})


@@ 35,11 51,11 @@ func (c *Connection) Run() {
			return true
		}
		// TODO: Only spawn proximate peers
		c.Conn.WriteJSON(&SpawnPeerMessage{
		c.Send(&SpawnPeerMessage{
			Message: Message{"spawn_peer"},
			Peer:    peer.Player,
		})
		peer.Conn.WriteJSON(&SpawnPeerMessage{
		peer.Send(&SpawnPeerMessage{
			Message: Message{"spawn_peer"},
			Peer:    c.Player,
		})


@@ 48,7 64,7 @@ func (c *Connection) Run() {

	// TODO: Only send proximate chunks
	for coords, chunk := range Map {
		c.Conn.WriteJSON(&ChunkDataMessage{
		c.Send(&ChunkDataMessage{
			Message: Message{"chunk_data"},
			Coords:  coords,
			Cells:   *chunk,


@@ 88,7 104,6 @@ func (c *Connection) Run() {
			SetCell(setCell.Coords, c.Player.Color)
			setCell.Color = c.Player.Color
			c.SendToPeers(&setCell)
			break;
		}
	}



@@ 96,13 111,14 @@ func (c *Connection) Run() {
		Message: Message{"despawn_peer"},
		PeerId: c.Player.Id,
	})
	c.outgoing <-nil
	conns.Delete(c)
}

func SendToEveryone(msg interface{}) {
	conns.Range(func(key interface{}, _ interface{}) bool {
		conn, _ := key.(*Connection)
		conn.Conn.WriteJSON(msg)
		conn.Send(msg)
		return true
	})
}


@@ 113,7 129,7 @@ func (c *Connection) SendToPeers(msg interface{}) {
		if conn == c {
			return true
		}
		conn.Conn.WriteJSON(msg)
		conn.Send(msg)
		return true
	})
}

M index.js => index.js +1 -0
@@ 361,6 361,7 @@ canvas.addEventListener('mouseup', e => {

canvas.addEventListener('contextmenu', e => {
  e.preventDefault();
  return false;
});

window.addEventListener('keydown', e => {