Golang crea un servidor de juegos para el propietario [8]: primero abre un servidor

Hay muchos marcos de servidor de juegos en golang. Generalmente, un cliente de un juego terminado necesita acceder al sistema de cuentas y otros sistemas clasificados.

En aras de la simplicidad, abramos el lado del servidor TCPServer más simple (los diversos marcos de servidor en la red son similares, y aquí elegimos usar el marco 266 tcp. En realidad, significa una cosa)

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 )
}

 

Debido a que el cliente necesita operar, debe tener una biblioteca con una interfaz, aquí elijo usar la biblioteca de la interfaz del cliente govcl

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")
}

//

Después del inicio, probablemente sea una interfaz como esta

 

Bibliotecas utilizadas en este artículo

go build github.com/266game/goserver
go build github.com/ying32/govcl
go build github.com/golang/protobuf

 

Supongo que te gusta

Origin blog.csdn.net/warrially/article/details/88796614
Recomendado
Clasificación