github.com/GeniusesGroup/libgo@v0.0.0-20220929090155-5ff932cb408e/achaemenid/network-application-multiplexer.go (about)

     1  /* For license and copyright information please see LEGAL file in repository */
     2  
     3  package achaemenid
     4  
     5  import (
     6  	"../protocol"
     7  	"../log"
     8  )
     9  
    10  // netAppMux (Network Application Multiplexer) and its methods act as multiplexer and route income packet to desire protocol handler!
    11  type netAppMux struct {
    12  	handlers [65536]protocol.NetworkApplicationHandler // TODO::: It use 256||512 KB of RAM on 32||64bit! Other alternative? map use more than this simple array.
    13  	lastUse  uint16
    14  }
    15  
    16  // SetNetworkApplicationHandler use to set or change specific handler!
    17  func (nam *netAppMux) SetNetworkApplicationHandler(protocolID protocol.NetworkApplicationProtocolID, nah protocol.NetworkApplicationHandler) {
    18  	if nam.handlers[protocolID] != nil {
    19  		log.Warn("Protocol handler with ID: ", protocolID, ", register before, Double check for any mistake to prevent unexpected behavior")
    20  	}
    21  	nam.handlers[protocolID] = nah
    22  	return
    23  }
    24  
    25  // GetNetworkApplicationHandler return the protocol handler for given ID!
    26  func (nam *netAppMux) GetNetworkApplicationHandler(protocolID protocol.NetworkApplicationProtocolID) (nah protocol.NetworkApplicationHandler) {
    27  	nah = nam.handlers[protocolID]
    28  	if nah == nil {
    29  		// TODO::: return not exist handler instead of nil handler
    30  	}
    31  	return
    32  }
    33  
    34  // DeleteNetworkApplicationHandler delete the handler from handlers.
    35  func (nam *netAppMux) DeleteNetworkApplicationHandler(protocolID protocol.NetworkApplicationProtocolID) {
    36  	nam.handlers[protocolID] = nil
    37  }
    38  
    39  // GetFreeProtocolID use to get free portID.
    40  // usually use to start connection to other servers in random other than standards ports number.
    41  func (nam *netAppMux) GetFreeProtocolID() (protocolID uint16) {
    42  	for i := 0; i < 65536; i++ {
    43  		nam.lastUse++
    44  		if nam.handlers[nam.lastUse] == nil {
    45  			return nam.lastUse
    46  		}
    47  	}
    48  	return 0
    49  }