There are many game server frameworks in golang.Generally, a client of a finished game needs to access the account system and other classified systems.
For the sake of simplicity, let's open the simplest TCPServer server side (the various server frameworks on the network are similar, and here we choose to use the 266 tcp framework. It actually means one thing)
package main
import (
"log"
"time"
connection "github.com/266game/goserver/Connection"
tcpserver "github.com/266game/goserver/TCPServer"
)
func main() {
// 启动服务器
pServer := tcpserver.NewTCPServer()
pServer.OnRead = func(pData *connection.TData) {
// 这里是服务器收到的内容
}
// 开启一个新的端口 12345
pServer.Start(":12345")
// 这里暂时弄一个5000小时的等待, 不然进程就直接关闭了.
time.Sleep(time.Hour * 5000 )
}
Because the client needs to operate, it must have a library with an interface, here I choose to use the govcl client interface library
package main
import (
"log"
connection "github.com/266game/goserver/Connection"
tcpclient "github.com/266game/goserver/TCPClient"
"github.com/ying32/govcl/vcl"
)
// TMainForm 主窗体
type TMainForm struct {
*vcl.TForm
Btn1 *vcl.TButton
pClient *tcpclient.TTCPClient
}
var mainForm *TMainForm
func main() {
vcl.Application.Initialize() // 应用初始化
vcl.Application.SetMainFormOnTaskBar(true) // 设置主窗口在任务栏上显示
vcl.Application.CreateForm(&mainForm) // 创建主窗口
vcl.Application.Run() // 程序运行
}
// -- TMainForm
// OnFormCreate 主窗口创建事件
func (self *TMainForm) OnFormCreate(sender vcl.IObject) {
self.SetCaption("这是一个游戏服务器")
self.Btn1 = vcl.NewButton(self) // 创建按钮
self.Btn1.SetParent(self) //设置爸爸
self.Btn1.SetBounds(10, 10, 88, 28) //设置位置
self.Btn1.SetCaption("开始连接") //
self.Btn1.SetOnClick(self.OnButtonClick) // 绑定按钮1点击事件
}
// OnButtonClick 按钮点击事件
func (self *TMainForm) OnButtonClick(sender vcl.IObject) {
// 创建一个客户端
pClient := tcpclient.NewTCPClient()
// 保存指针
self.pClient = pClient
// 客户端收到消息事件
pClient.OnRead = func(*connection.TData) {
}
// 连接成功事件
pClient.OnConnect = func(pConn *connection.TConnection) {
self.Btn1.SetCaption("连接成功")
log.Println(pConn.GetTCPConn().RemoteAddr().String() + "连接成功")
}
self.Btn1.SetCaption("连接中")
self.Btn1.SetEnabled(false)
// 可以开始连接了
pClient.Connect("127.0.0.1:12345")
}
//
After startup, it's probably an interface like this
Libraries used in this article
go build github.com/266game/goserver
go build github.com/ying32/govcl
go build github.com/golang/protobuf