moguding / link

A simple golang network library for packet based persistent connection communication.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Introduction

This is a simple network library for Go.

It focus on packet based persistent connection communication.

It provide a packet splitting protocol like Erlang's {packet: N} in default. And supported custom packet splitting protocol.

But it didn't limit the encode or decode format of the request and response.

Also this library provide session management and broadcast features to make your life easy.

How to install

go get github.com/funny/link

How to use

Choose a protocol for your project.

proto := link.PacketN(2, binary.BigEndian)

Setup a server on port 8080 and set protocol.

server, _ := link.Listen("tcp", "0.0.0.0:8080", proto)

Handle incoming connections. And setup a message handler on the new session.

server.AcceptLoop(func(session *Session) {
	fmt.Println("session start")

	session.ReadLoop(func(session *Session, msg []byte) {
		fmt.Printf("new message: %s\n", msg)
	})

	fmt.Println("session closed")
})

Use the same protocol dial to the server.

proto := link.PacketN(2, binary.BigEndian)

client, _ := link.Dial("tcp", "127.0.0.1:8080", proto)

Implement a message type.

type TestMessage struct {
	Message string
}

func (msg TestMessage) RecommendPacketSize() uint {
	return uint(len(msg.Message))
}

func (msg TestMessage) AppendToPacket(packet []byte) []byte {
	return append(packet, msg.Message...)
}

Send a message to server.

client.Send(TestMessage{ "Hello World!" })

Examples

Document

Let's Go!

About

A simple golang network library for packet based persistent connection communication.

License:Do What The F*ck You Want To Public License