【GO语言】棋牌游戏服务器

暂未完成调试,只能跑通简单测试

目录结构

cgss-{src-{-cg{-center.go

                                          -centerclient.go

                                                -player.go

                           -ipc{-server.go

                                                    -client.go

                                                     -ipc_test.go

                                         -cgss.go

server.go

// server.go
package ipc

import (
	"encoding/json"
	"fmt"
)

type Request struct {
	Method string "method"
	Params string "params"
}
type Response struct {
	Code string "code"
	Body string "code"
}
type Server interface {
	Name() string
	Handle(method, params string) *Response
}
type IpcServer struct {
	Server
}

func NewIpcServer(server Server) *IpcServer {
	return &IpcServer{server}
}
func (server *IpcServer) Connect() chan string {
	session := make(chan string, 0)
	go func(c chan string) {
		for {
			request := <-c
			if request == "CLOSE" {
				break
			}
			var req Request
			err := json.Unmarshal([]byte(request), &req)
			if err != nil {
				fmt.Println("无效的请求格式:", request)
			}
			resp := server.Handle(req.Method, req.Params)
			b, err := json.Marshal(resp)
			c <- string(b)
		}
		fmt.Println("会议关闭")
	}(session)
	fmt.Println("新的会议已经建立。")
	return session
}

client.go

// client
package ipc

import "encoding/json"

type IpcClient struct {
	conn chan string
}

func NewIpcClient(server *IpcServer) *IpcClient {
	c := server.Connect()
	return &IpcClient{c}
}
func (client *IpcClient) Call(method, parmas string) (resp *Response, err error) {
	req := &Request{method, parmas}
	var b []byte
	b, err = json.Marshal(req)
	if err != nil {
		return
	}
	client.conn <- string(b)
	str := <-client.conn
	var resq1 Response
	err = json.Unmarshal([]byte(str), &resq1)
	resp = &resq1
	return
}
func (client *IpcClient) Close() {
	client.conn <- "CLOSE"
}

ipc_test.go

// ipc_test
package ipc

import (
	"testing"
)

type EchoServer struct {
}

func (server *EchoServer) Handle(request string) string {
	return "ECHO" + request
}
func (server *EchoServer) Name() string {
	return "EchoServer"
}
func TestIpc(t *testing.T) {
	server := NewIpcServer(&EchoServer{})
	client1 := NewIpcClient(server)
	client2 := NewIpcClient(server)
	resq1 := client1.Call("From Client1")
	resq2 :=client2.Call("From Client2")
	if resq1 !="Echo:From Client1"||res2!="Echo:From Client2"{
		t.Error("IpcClient.Call fail","resq1:",resq1,"resq2:"resq2)
	}
	client1.Close()
	client2.Close()
}

player.go

// palyer
package cg

import (
	"fmt"
)

type Player struct {
	Name  string "name"
	Level int    "level"
	Exp   int    "exp"
	Room  int    "room"

	mq chan *Message //等待接受的数据
}

func NewPlayer() *Player {
	m := make(chan *Message, 1024)
	player := &Player{"", 0, 0, 0, m}
	go func(p *Player) {
		for {
			msg := <-p.mq
			fmt.Println(p.Name, "Received message:", msg.Content)
		}
	}(player)
	return player
}

center.go

// center
package cg

import (
	"encoding/json"
	"errors"
	"ipc"
	"sync"
)

var _ ipc.Server = &CenterServer{} //确认实现SERVER接口
type Message struct {
	From    string "from"
	To      string "to"
	Content string "content"
}
type CenterServer struct {
	servers map[string]ipc.Server
	players []*Player
	rooms   int
	mutex   sync.RWMutex //加入读写锁
}

func NewCenterServer() *CenterServer {
	servers := make(map[string]ipc.Server)
	players := make([]*Player, 0)
	return &CenterServer{servers: servers, players: players}
}
func (server *CenterServer) addPlayer(params string) error {
	player := NewPlayer()
	err := json.Unmarshal([]byte(params), &player)
	if err != nil {
		return err
	}
	server.mutex.Lock()
	defer server.mutex.Unlock()

	server.players = append(server.players, player)
	return nil
}
func (server *CenterServer) removePlayer(params string) error {
	server.mutex.Lock()
	defer server.mutex.Unlock()
	for i, v := range server.players {
		if v.Name == params {
			if len(server.players) == 1 {
				server.players = make([]*Player, 0)

			} else if i == len(server.players)-1 {
				server.players = server.players[:i-1]
			} else if i == 0 {
				server.players = server.players[1:]
			} else {
				server.players = append(server.players[:i-1], server.players[i+1:]...)
			}
			return nil
		}

	}
	return errors.New("玩家没找到")
}
func (server *CenterServer) listPlayer(params string) (players string, err error) {
	server.mutex.RLock()
	defer server.mutex.RUnlock()
	if len(server.players) > 0 {
		b, _ := json.Marshal(server.players)
		players = string(b)
	} else {
		err = errors.New("没有玩家在线")
	}
	return
}
func (server *CenterServer) broadcast(params string) error {
	var message Message
	err := json.Unmarshal([]byte(params), &message)
	if err != nil {
		return err
	}
	server.mutex.Lock()
	defer server.mutex.Unlock()
	if len(server.players) > 0 {
		for _, player := range server.players {
			player.mq <- &message
		}
	} else {
		err = errors.New("没有玩家在线")
	}
	return err
}
func (server *CenterServer) Handle(method, params string) *ipc.Response {
	switch method {
	case "addplayer":
		err := server.addPlayer(params)
		if err != nil {
			return &ipc.Response{Code: err.Error()}
		}
	case "removeplayer":
		err := server.removePlayer(params)
		if err != nil {
			return &ipc.Response{Code: err.Error()}
		}
	case "listplayer":
		players, err := server.listPlayer(params)
		if err != nil {
			return &ipc.Response{Code: err.Error()}
		}
		return &ipc.Response{"200", players}
	case "broadcast":
		err := server.broadcast(params)
		if err != nil {
			return &ipc.Response{Code: err.Error()}
		}
		return &ipc.Response{Code: "200"}
	default:
		return &ipc.Response{Code: "404", Body: method + ":" + params}
	}
	return &ipc.Response{Code: "200"}
}
func (server *CenterServer) Name() string {
	return "CenterServer"
}

centerclient.go

// centerclient
package cg

import (
	"encoding/json"
	"errors"
	"ipc"
)

type CenterClient struct {
	*ipc.IpcClient
}

func (client *CenterClient) AddPlayer(player *Player) error {
	b, err := json.Marshal(*player)
	if err != nil {
		return err
	}
	resp, err := client.Call("addplayer", string(b))
	if err == nil && resp.Code == "200" {
		return nil
	}
	return err
}
func (client *CenterClient) RemovePlayer(name string) error {
	ret, _ := client.Call("RemovePlayer", name)
	if ret.Code == "200" {
		return nil
	}
	return errors.New(ret.Code)
}
func (client *CenterClient) ListPlayer(params string) (ps []*Player, err error) {
	resp, _ := client.Call("listplayer", params)
	if resp.Code != "200" {
		err = errors.New(resp.Code)
	}
	err = json.Unmarshal([]byte(resp.Body), &ps)
	return
}
func (client *CenterClient) Broadcast(message string) error {
	m := &Message{Content: message}
	b, err := json.Marshal(m)
	if err != nil {
		return err
	}
	resp, _ := client.Call("broadcost", string(b))
	if resp.Code == "200" {
		return nil
	}
	return errors.New(resp.Code)
}

cgss.go

// cgss
package main

import (
	"bufio"
	"cg"
	"fmt"
	"ipc"
	"os"
	"strconv"
	"strings"
)

var CenterClient *cg.CenterClient

func startCenterService() error {
	server := ipc.NewIpcServer(&cg.CenterServer{})
	client := ipc.NewIpcClient(server)
	CenterClient = &cg.CenterClient{client}

	return nil
}
func Help(args []string) int {
	fmt.Println(`
		Commands:
			login
			logout
			send
			listplayer
			quit(q)
			help(h)
	`)
	return 0
}
func Quit(args []string) int {
	return 1
}
func Logout(args []string) int {
	if len(args) != 2 {
		fmt.Println("USAGE:logout ")
		return 0
	}
	CenterClient.RemovePlayer(args[1])
	return 0
}
func Login(args []string) int {
	if len(args) != 4 {
		fmt.Println("USAGE:login")
		return 0
	}
	level, err := strconv.Atoi(args[2])
	if err != nil {
		fmt.Println("invalid parameter: should be an integer")
		return 0
	}
	exp, err := strconv.Atoi(args[3])
	if err != nil {
		fmt.Println("invalid parameter: should be an integer")
		return 0
	}
	player := cg.NewPlayer()
	player.Name = args[1]
	player.Level = level
	player.Exp = exp

	err = CenterClient.AddPlayer(player)
	if err != nil {
		fmt.Println("failed adding player", err)
	}
	return 0
}
func ListPlayer(args []string) int {
	ps, err := CenterClient.ListPlayer("")
	if err != nil {
		fmt.Println("failed. ", err)
	} else {
		for i, v := range ps {
			fmt.Println(i+1, ":", v)
		}
	}
	return 0
}
func Send(args []string) int {
	message := strings.Join(args[1:], " ")
	err := CenterClient.Broadcast(message)
	if err != nil {
		fmt.Println("failed", err)
	}
	return 0
}
func GetCommandHandlers() map[string]func(args []string) int {
	return map[string]func([]string) int{
		"help":       Help,
		"h":          Help,
		"quit":       Quit,
		"q":          Quit,
		"login":      Login,
		"logout":     Logout,
		"listplayer": ListPlayer,
		"send":       Send,
	}
}
func main() {
	fmt.Println("休闲游戏服务器解决方案")
	startCenterService()
	Help(nil)
	r := bufio.NewReader(os.Stdin)
	handlers := GetCommandHandlers()
	for {
		fmt.Print("commod>")
		b, _, _ := r.ReadLine()
		line := string(b)
		tokens := strings.Split(line, " ")
		if handler, ok := handlers[tokens[0]]; ok {
			ret := handler(tokens)
			if ret != 0 {
				break
			}
		} else {
			fmt.Println("unknown command", tokens[0])
		}
	}
}

测试方式 login 人名 等级 经验

                logout  人名

                listplayer

                send message

                q

你可能感兴趣的:(go,game,算法)