Cribbage server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
1.9 KiB

package main
import (
"log"
"net"
"net/http"
"sync"
"github.com/gorilla/websocket"
)
var websocketUpgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type CribServer struct {
clients []*Client
clientqueue []*Client
clientqueuealert chan bool
sync.RWMutex
}
func (cs *CribServer) handleReadWebSocket(w http.ResponseWriter, r *http.Request) {
log.Println("New WebSocket")
c, err := websocketUpgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("WebSocket upgrade error:", err)
return
}
defer c.Close()
client := &Client{ConnType: ClientWebsocket, ConnWebsocket: c}
client.initialize()
cs.addClient(client)
}
func (cs *CribServer) listenWebSocket(address string, path string) {
http.HandleFunc(path, cs.handleReadWebSocket)
http.ListenAndServe(address, nil)
}
func (cs *CribServer) addClient(client *Client) {
cs.Lock()
cs.clients = append(cs.clients, client)
cs.Unlock()
go client.processRead()
go client.handleWrite()
cs.queueClient(client)
client.handleRead()
}
func (cs *CribServer) listenTelnet(address string) {
ln, err := net.Listen("tcp", address)
if err != nil {
log.Println(err)
return
}
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
client := &Client{ConnType: ClientTelnet, ConnTelnet: conn}
client.initialize()
go cs.addClient(client)
}
}
func (cs *CribServer) queueClient(client *Client) {
cs.Lock()
cs.clientqueue = append(cs.clientqueue, client)
cs.Unlock()
cs.clientqueuealert <- true
}
func (cs *CribServer) matchPlayers() {
for range cs.clientqueuealert {
cs.Lock()
if len(cs.clientqueue) > 1 {
go cs.startGame(cs.clientqueue[0], cs.clientqueue[1])
cs.clientqueue = cs.clientqueue[2:]
}
cs.Unlock()
}
}
func (cs *CribServer) startGame(player1, player2 *Client) {
game := NewGame(player1, player2)
game.playGame()
}