Skip to content

lim-yoona/tcpack

Repository files navigation

tcpack

Go Reference GitHub Go Report GitHub release (with filter) Mentioned in Awesome Go

English | 简体中文

tcpack is an application protocol based on TCP to Pack and Unpack bytes stream in go (or 'golang' for search engine friendliness) program.

What dose tcpack do?

As we all know, TCP is a transport layer protocol oriented to byte streams. Its data transmission has no clear boundaries, so the data read by the application layer may contain multiple requests and cannot be processed.

tcpack is to solve this problem by encapsulating the request data into a message, packaging it when sending and unpacking it when receiving.

notice: It is unsafe to use a packer to read and write messages concurrently on the same connection. Do not do this, as it will have unpredictable consequences!

If you want to use multiple packagers based on the same TCP connection to send and receive messages concurrently, please use safetcpack.

What's in the box?

This library provides a packager which support Pack and Unpack.

Installation Guidelines

  1. To install the tcpack package, you first need to have Go installed, then you can use the command below to add tcpack as a dependency in your Go program.
go get -u github.com/lim-yoona/tcpack
  1. Import it in your code:
import "github.com/lim-yoona/tcpack"

Usage

package main

import "github.com/lim-yoona/tcpack"

func main() {
	// Create a packager
	mp := tcpack.NewMsgPack(8, tcpConn)

	// Pack and send a message
	msg := tcpack.NewMessage(0, uint32(len([]byte(data))), []byte(data))
	num, err := mp.Pack(msg)

	// Unpack and receive a message
	msg, err := mp.Unpack()
}

Support JSON

type Person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

// Create a packager
mp := tcpack.NewMsgPack(8, tcpConn)

// data JSON Marshal
data := &Person{
	Name: "jack",
	Age:  20,
}
dataJSON, _ := json.Marshal(data)

// Pack and send a message
msgSend := tcpack.NewMessage(0, uint32(len(dataJSON)), dataJSON)
num, err := mp.Pack(msgSend)

// Unpack and receive a message
msgRsv, err := mp.Unpack()

// JSON UnMarshal
var dataRsv Person
json.Unmarshal(msgRsv.GetMsgData(), &dataRsv)

Examples

Here are some Examples.