使用GoLang开发游戏服务器(一)

实现最简单的服务器和客户端的通信

在这里插入图片描述

IServer

type IServer interface {
	Start()
	Stop()
	Serve()
}

server

type Server struct {
	Name      string
	IpVersion string
	Ip        string
	Port      int
}

func (s *Server) Start() {
	go func() {
		addr, err := net.ResolveTCPAddr(s.IpVersion, fmt.Sprintf("%s:%d", s.Ip, s.Port))
		if err != nil {
			fmt.Println("Resolve TCP Address Error", err)
			return
		}
		listener, err := net.ListenTCP(s.IpVersion, addr)
		if err != nil {
			fmt.Println("Listen Error", err)
			return
		}
		fmt.Println("Server Start !")
		for true {
			conn, err := listener.Accept()
			if err != nil {
				fmt.Println("Account Error", err)
				continue
			}

			go func() {
				for true {
					buf := make([]byte, 512)
					count, err := conn.Read(buf)
					if err != nil {
						fmt.Println("Read Error", err)
						continue
					}
					fmt.Printf("客户端发来的数据:%s\n", buf[:count])

					if _, err := conn.Write(buf[:count]); err != nil {
						fmt.Println("Write Error", err)
						continue
					}
				}
			}()
		}
	}()
}

func (s *Server) Stop() {

}

func (s *Server) Serve() {
	s.Start()
	//TODO:做一些服务器启动之后的额外业务
	select {}
}

func NewServer(name string) ziface.IServer {
	s := &Server{
		Name:      name,
		IpVersion: "tcp4",
		Ip:        "192.168.0.4",
		Port:      8080,
	}
	return s
}

Dome的测试

Client和Server分别是Dome的客户端和服务端
在这里插入图片描述

  • Client
func main() {
	fmt.Println("Client Start...")
	time.Sleep(time.Second)
	conn, err := net.Dial("tcp", "106.13.203.64:8080")
	if err != nil {
		fmt.Println("Client Start Error", err)
		return
	}

	//创建子Goroutine去读取数据
	go func() {
		for true {
			buf := make([]byte, 512)
			count, err := conn.Read(buf)
			if err != nil {
				fmt.Println("Read Error...", err)
				return
			}
			fmt.Printf("Server Call Back: %s, count: %d\n", buf[:count], count)
		}
	}()

	//让主Goroutine阻塞,去写数据
	for true {
		str := ""
		fmt.Scanln(&str)
		_, err := conn.Write([]byte(str))
		if err != nil {
			fmt.Println("Write Error...", err)
			return
		}
	}
}
  • Server
func main() {
	s := znet.NewServer("[zinx v0.1] Server")
	s.Serve()
}