Categorygithub.com/giterlab/tcpnetwork
modulepackage
0.0.0-20190322085543-6a08d366a292
Repository: https://github.com/giterlab/tcpnetwork.git
Documentation: pkg.go.dev

# README

tcpnetwork

A simple golang tcp server/client.

purpose

Provide a simple model to process multi connections.You can use tcpnetwork as a server and as a client, then process all event in a output channel, so you just need one routine (maybe main routine) to process all things.

protobuf support

You can directly use tcpnetwork to send a protobuf message, and set a hook to unserialize your protobuf message.

asynchoronously process event

A simple way to process connection event is to process all event in one routine by reading the event channel tcpnetwork.GetEventQueue().

server := tcpnetwork.NewTCPNetwork(1024, tcpnetwork.NewStreamProtocol4())
err = :server.Listen(kServerAddress)
if nil != err {
	return panic(err)
}

for {
	select {
	case evt, ok := <-server.GetEventQueue():
		{
			if !ok {
				return
			}

			switch evt.EventType {
			case tcpnetwork.KConnEvent_Connected:
				{
					log.Println("Client ", evt.Conn.GetRemoteAddress(), " connected")
				}
			case tcpnetwork.KConnEvent_Close:
				{
					log.Println("Client ", evt.Conn.GetRemoteAddress(), " disconnected")
				}
			case tcpnetwork.KConnEvent_Data:
				{
					evt.Conn.Send(evt.Data, 0)
				}
			}
		}
	case <-stopCh:
		{
			return
		}
	}
}

synchronously process event

When you need to process event in every connection routine, you can set a synchronously process function callback by setting the Connection's SetSyncExecuteFunc.

Returning true in this callback function represents the processed event will not be put in the event queue.

client := tcpnetwork.NewTCPNetwork(1024, tcpnetwork.NewStreamProtocol4())
conn, err := client.Connect(kServerAddress)
conn.SetSyncExecuteFunc(...)

example

  • echo server

     // echo server routine
     func echoServer() (*tcpnetwork.TCPNetwork, error) {
     	var err error
     	server := tcpnetwork.NewTCPNetwork(1024, tcpnetwork.NewStreamProtocol4())
     	err = server.Listen(kServerAddress)
     	if nil != err {
     		return nil, err
     	}
     
     	return server, nil
     }
     
     func routineEchoServer(server *tcpnetwork.TCPNetwork, wg *sync.WaitGroup, stopCh chan struct{}) {
     	defer func() {
     		log.Println("server done")
     		wg.Done()
     	}()
     
     	for {
     		select {
     		case evt, ok := <-server.GetEventQueue():
     			{
     				if !ok {
     					return
     				}
     
     				switch evt.EventType {
     				case tcpnetwork.KConnEvent_Connected:
     					{
     						log.Println("Client ", evt.Conn.GetRemoteAddress(), " connected")
     					}
     				case tcpnetwork.KConnEvent_Close:
     					{
     						log.Println("Client ", evt.Conn.GetRemoteAddress(), " disconnected")
     					}
     				case tcpnetwork.KConnEvent_Data:
     					{
     						evt.Conn.Send(evt.Data, 0)
     					}
     				}
     			}
     		case <-stopCh:
     			{
     				return
     			}
     		}
     	}
     }
     
    
  • echo client

      // echo client routine
      func echoClient() (*tcpnetwork.TCPNetwork, *tcpnetwork.Connection, error) {
      	var err error
      	client := tcpnetwork.NewTCPNetwork(1024, tcpnetwork.NewStreamProtocol4())
      	conn, err := client.Connect(kServerAddress)
      	if nil != err {
      		return nil, nil, err
      	}
      
      	return client, conn, nil
      }
      
      func routineEchoClient(client *tcpnetwork.TCPNetwork, wg *sync.WaitGroup, stopCh chan struct{}) {
      	defer func() {
      		log.Println("client done")
      		wg.Done()
      	}()
      
      EVENTLOOP:
      	for {
      		select {
      		case evt, ok := <-client.GetEventQueue():
      			{
      				if !ok {
      					return
      				}
      				switch evt.EventType {
      				case tcpnetwork.KConnEvent_Connected:
      					{
      						log.Println("Press any thing")
      						atomic.StoreInt32(&serverConnected, 1)
      					}
      				case tcpnetwork.KConnEvent_Close:
      					{
      						log.Println("Disconnected from server")
      						atomic.StoreInt32(&serverConnected, 0)
      						break EVENTLOOP
      					}
      				case tcpnetwork.KConnEvent_Data:
      					{
      						text := string(evt.Data)
      						log.Println(evt.Conn.GetRemoteAddress(), ":", text)
      					}
      				}
      			}
      		case <-stopCh:
      			{
      				return
      			}
      		}
      	}
      }
    

See more example in cmd directory.

license

MIT

# Packages

No description provided by the author

# Functions

No description provided by the author
NewStreamProtocol4 creates a StreamProtocol4.
NewTCPNetwork creates a TCPNetwork object.
SetLogger Set the custom logger.
SetPbUnserializeHook set the global protobuf unserialize function.

# Constants

All connection event.
All connection event.
All connection event.
All connection event.
All connection event.
All connection event.
All connection event.
Copy the send buffer.
Do not append stream header.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Variables

No description provided by the author
No description provided by the author

# Structs

Connection is a wrap for net.Conn and process read and write task of the conn When event occurs, it will call the eventQueue to dispatch event.
ConnEvent represents a event occurs on a connection, such as connected, disconnected or data arrived.
StreamProtocol2 implement a simple binary stream protocol with 2 bytes header as packet length Binary format : | 2 byte (total stream length) | data ..
StreamProtocol4 implement a simple binary stream protocol with 4 bytes header as packet length Binary format : | 4 byte (total stream length) | data ..
TCPNetwork manages all server and client connections.
TCPNetworkConf config the TCPNetwork.

# Interfaces

IEventHandler is callback interface to process connection's event.
IEventQueue queues all connection's events.
ILogger is an interface use for log message.
IStreamProtocol implement the protocol of the binary data stream for unpacking packet.
IUnpacker unpack the binary stream to replace the internal unpack process.

# Type aliases

FuncPbUnserializeHook is a function to unserialize binary data to protobuf message.
Sync event callback If return true, this event will not be sent to event channel If return false, this event will be sent to event channel again.