示例#1
0
文件: client.go 项目: boj/goenet
func main() {
	if goenet.Initialize() == 0 {
		defer goenet.Deinitialize()

		address := &goenet.ENetAddress{}
		address.SetHostName(HOST)
		address.SetPort(5555)

		event := &goenet.ENetEvent{}

		client := goenet.NewHost(nil, 1, 2, 5760/8, 1440/8)
		if client == nil {
			panic("Client Initialization Error")
		} else {
			defer client.Destroy()
		}

		peer := client.Connect(address, 2, 0)
		if peer == nil {
			panic("Client could not connect to host")
		} else {
			log.Print("Client started\n")
		}

		if client.Service(event, 1000) > 0 && event.EventType() == goenet.ENET_EVENT_TYPE_CONNECT {
			log.Print("Connected to server\n")
		} else {
			panic("Failed to connect to server")
		}

		for i := 0; i < 10; i++ {
			data := []byte("Hello")
			packet := goenet.NewPacket(data, len(data), goenet.ENET_PACKET_FLAG_RELIABLE)
			peer.Send(0, packet)
		}

		for {
			for client.Service(event, 1000) > 0 {
				switch event.EventType() {
				case goenet.ENET_EVENT_TYPE_RECEIVE:
					length := event.Packet().DataLength()
					packetData := string(event.Packet().Data())
					channel := event.ChannelID()
					log.Printf("packet - length: %d, data: %s, channel: %d\n", length, packetData, channel)
					event.Packet().Destroy() // clean up
					break
				case goenet.ENET_EVENT_TYPE_DISCONNECT:
					log.Printf("Client disconnected by server\n")
					break
				}
			}
		}
	}
}
示例#2
0
文件: server.go 项目: boj/goenet
func main() {
	player := &Player{
		Name: "Player1",
	}

	if goenet.Initialize() == 0 {
		defer goenet.Deinitialize()

		address := &goenet.ENetAddress{}
		address.SetHost(goenet.ENET_HOST_ANY)
		address.SetPort(5555)

		event := &goenet.ENetEvent{}

		server := goenet.NewHost(address, 32, 2, 0, 0)
		if server == nil {
			panic("Server Initialization Error")
		} else {
			defer server.Destroy()
		}

		log.Print("Server started\n")
		for {
			for server.Service(event, 1000) > 0 {
				switch event.EventType() {
				case goenet.ENET_EVENT_TYPE_CONNECT:
					peer := event.Peer()
					log.Println(player)
					peer.SetData(player)
					log.Printf("Client connected: %d\n", peer.ConnectID())
					break
				case goenet.ENET_EVENT_TYPE_RECEIVE:
					peer := event.Peer()
					// player := peer.Data().(*Player)
					length := event.Packet().DataLength()
					packetData := string(event.Packet().Data())
					channel := event.ChannelID()
					log.Printf("packet - length: %d, data: %s, channel: %d", length, packetData, channel)
					peer.Send(channel, goenet.NewPacket([]byte(packetData), length, goenet.ENET_PACKET_FLAG_RELIABLE))
					event.Packet().Destroy() // clean up
					break
				case goenet.ENET_EVENT_TYPE_DISCONNECT:
					log.Printf("Client disconnected\n")
					break
				}
			}
		}
	}
}