This is a creation in Article, where the information may have evolved or changed.
Stpro a simple communication framework based on TCP protocol implementation
A skeleton for communication based on TCP
Github:https://github.com/by-zhang/s ... Thick-skinned star
Characteristics
- Introduction to go package to use
- CRC verification is implemented to ensure the integrity and correctness of data transmission.
- Simple and straightforward invocation method
Quick Start
1. Introduction
import "stpro"
2. Server-side
/** three steps to build server 1 defines the data structure of any struct, which must contain Pmap, phost two fields, where Phost is the server-side ip+port stitching string, PMAP is the custom packet type and number The mapping of the package name. 2 The instantiated object assigns a value to the field, implementing a packet processing method that corresponds to the defined ' package name ', which must be ' p[package name ', as the type package is handled as PType. method, define the data processing logic, the input input is []byte type. 3 Stpro. New () Incoming instantiated objects, such as no error, the server starts to listen, and according to the logic you defined to process the packet, return the response data. **/Package Main import ("FMT" "Stpro") type Server struct {phost string Pmap Map[uint8]string} func (M Server) Ptype (in []byte) (out []byte) {fmt. PRINTF ("The client sent a type package:%s\n", in)/** process ... **/bytes: = []byte ("hello1") return bytes} func (M Server) Pname (in []byte] (out []byte) {fmt. PRINTF ("Client sent to name package:%s\n", in)/** process ... **/bytes: = []byte ("Hello2") return bytes} func Main () {m: = model{phost: ": 9091", Pmap:make (map[uint8]string),} m.pmap[0x [] = "type" m.pmap[0x02] = "Name" ERR: = Stpro. New (m) if err! = Nil {fmt. PRINTLN (ERR)}}
3.client Terminal
/** three sets up the client 1 data structure with the service side. 2 P[type] method is the processing method that receives the response data after the corresponding packet is sent. 3 instantiates the object and calls the Send (type byte, content []byte) method for sending data to the client, and the received data is then customized to be treated as defined above. **/Package Main import ("FMT" "Stpro") type Client struct {phost string Pmap Map[byte]string} func (c Client) Ptype (in []byte) {fmt. Printf ("received the type Package's reply:%s\n", IN)} func (C-Client) Pname (in []byte) {fmt. Printf ("received the name package's reply:%s\n", IN)} func main () {client, err: = Stpro. Newclient (client{phost: "192.168.1.106:9091", pmap:map[byte]string{0x01: "Type", 0x02: "Name",},}) if err! = Nil {fmt. PRINTLN (ERR) return} err = client. Send (0x02, []byte ("Jintianzhenhao")) if err! = Nil {fmt. PRINTLN (ERR) return} err = client. Send (0x01, []byte ("jintianzhenhao3333")) If err! = Nil {fmt. PRINTLN (ERR) return}}