ezcomm

package module
v0.0.0-...-c201301 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2024 License: Apache-2.0 Imports: 27 Imported by: 0

README

EZComm

TCP/UDP/http, client & server all-in-one, with GUI or flow script. README in other language(-s): 简体中文

Home page of EZ project

Getting started

  • Go to Sourceforge for releases of prebuilt binaries.
  • Go to GitLab for releases of source code.
GUI
  • Steps 1-4 as an http server.
  • Steps 3,5-7 as a TCP/UDP client/server.
  • Steps 8-9 are configuration and script related.
  1. LAN shows all local interfaces with HTTP port we are listening on. tab LAN
  2. Click one item to copy it and open clipboard as address in a web browser. You can read readme or other info of this app with links then, exchange texts between browser server and clients, or view app's files. tab LAN
  3. To interact between two devices within same network, use either LAN/HTTP or interactive/files/TCP/UDP mode. To ease discovery of each other, click "Look for a peer" to show its address and port on the other. Choosing the item on the other device will copy the IP to remote address in interactive and files tab.
  4. HTTP shows the server created as in LAN. tab HTTP
  5. interactive mixes TCP/UDP client and server and sends/receives text. tab interactive 5.1. choose udp or tcp. 5.2. input local/remote address & port as needed. Local IP defaults to all interfaces and port defaults a system-chosen one. 5.3. choose listen to run as a server or send as a client.
  6. files sends/receives files between TCP/UDP client and server. tab files
  7. Downloads shows files in app's directory for files. tab Downloads
  8. log shows logging for assistance. tab log
  9. config contains anti-attack, language/font settings and flow switch. tab config

Source code under guiFyne directory uses Fyne for graphical UI to support cross-platforms.

Features
  • TCP/UDP/HTTP
  • client/server. send to different clients with different text as a server.
  • flow script to automatically listen, accept, receive and send messages or files.
    • file transfer. files or pieces are encapsulated to avoid confusion with text messages.
  • peer discovery in LAN
  • incoming/outgoing message history
  • anti-flood to neglect frequent incoming traffic from same IP
  • customizable and in-built fonts
  • multilingual interface. Current languages (mainly translated by Bing Translator from English and Chinese Simplified):
    • English
    • Spanish
    • Japanese
    • Chinese simplified (CN)
    • Chinese traditional (TW)
command line

source code under cmd directory. only flow mode supported.

  • Run it with "-h" to show command line parameters.
  • Run it with "-flow" parameter with flow file name to run with no graphical UI but the script only. Refer to sample*.xml to check how to write a flow script.

Code Building

For requirement on version of Go, refer to go.mod under root directory, and guiFyne, if GUI is needed.

CMD builds

Run build.sh or build.bat under cmd directory, on Linux or Windows, respectively.
Both EZComm_cmd for Linux and EZComm_cmd.exe for Windows will be generated with build.sh.

A parameter is version number in form of X.X.X, which defaults to 0.0.0. This is optional for build.sh.
If it exists, another optional parameter is build number. It defaults to current date for build.sh.

GUI builds

Refer to Fyne for more details on this GUI solution.

Prequisites

  • GCC is required. Refer to Prerequisites of Fyne for different platforms.
  • Run go install fyne.io/fyne/v2/cmd/fyne@latest
  • Run go install github.com/fyne-io/fyne-cross@latest if cross compiling is needed.

Build script

  • Run build.sh under guiFyne directory.
batch build for GUI on Windows, Liunx and Android, and CMD on Windows and Linux

Run build.sh under root directory. If a version in form of X.X.X is provided as a parameter, it will be used and it will be retail build, otherwise, it is a debug buid by default. In case a version is provided, a build number can be provided furthermore.

WEB builds

Though it does not function, it can also run in a browser with fyne serve or fyne package -os web. Details are in Fyne declares to support web builds.

This needs bon-ami/go-findfonts to build, so I "replace" flopp/go-findfonts in module settings. These libraries are same in other aspects.

Issues, Security & Tests

Tracked by Issues on GitLab

Tested and auto-built on GitLab

Security Status (not real-time)

Requirements and milestones

Requirements Milestones

EULA, License

Refer to COPYRIGHT for Explicit Distribution Declaration in addition to Apache V2.0.

Most translations by Bing

Built-in fonts are from following sites.

similar project(s)

  • LocalSend for msg/file exchanging, developed with flutter

Documentation

Index

Constants

View Source
const (
	// EzcName app name, such as for log file
	EzcName = "EZComm"
	// EzcURL URL of homepage
	EzcURL = "https://gitlab.com/bon-ami/ezcomm"
	// LogExt log file extension
	LogExt = ".log"
	// Localhost default peer address
	Localhost = "localhost" // use "" instead to listen on all interfaces
	// DefBrdAdr address for broadcast in lan discovery
	DefBrdAdr = "255.255.255.255" // broadcast addr
	// StrUDP is UDP protocol. otherwise, udp4, udp6, etc.
	StrUDP = "udp"
	// StrTCP is TCP protocol. otherwise, tcp4, tcp6, etc.
	StrTCP = "tcp"
	// DefAntFldLmt default anti-flood limit to tolerate a peer
	DefAntFldLmt = 10
	// DefAntFldPrd default anti-flood period to block a peer
	DefAntFldPrd = 60
)
View Source
const (
	// FileIDMax max file ID
	FileIDMax = 255
	// FileIDMin min file ID
	FileIDMin = 1
	// FileHdr1stLen min file header length
	FileHdr1stLen = 6
	// FileHdrRstLen min file header length
	FileHdrRstLen = 6
)
View Source
const (
	// FlowActRcv action receive
	FlowActRcv = "receive"
	// FlowActSnd action send
	FlowActSnd = "send"

	// FlowVarSign sign of vars
	FlowVarSign = "%"
	// FlowVarSep separator for vars
	FlowVarSep = "."
	// FlowVarLst var listen
	FlowVarLst = "listen"
	// FlowVarLcl var local
	FlowVarLcl = "local"
	// FlowVarPee var peer
	FlowVarPee = "peer"
	// FlowVarFil var file
	FlowVarFil = "file"
	// FlowVarScr var script
	FlowVarScr = "script"

	// FlowRcvLen is the size of receive buffer
	FlowRcvLen = 1024 * 1024 // must > FileHdr1stLen+len(EzcName)
	// FlowComLen is the size of the queue between EZComm and UI
	FlowComLen = 99
	// FlowFilLen is the size of send buffer for files
	FlowFilLen = 1024 * 1024
)
View Source
const (
	// FlowParseValSimple is a string without <FlowVarSign>
	FlowParseValSimple = iota
	// FlowParseValSign is for <FlowVarSign><string><FlowVarSign>
	FlowParseValSign
	// FlowParseValVar is for <FlowVarSign><xml tag name of FlowConnStruc/FlowStepStruc><FlowVarSign><string><FlowVarSign>
	FlowParseValVar
)
View Source
const (
	// FlowChnLst is not used by EZ Comm
	FlowChnLst = iota
	// FlowChnEnd is to end a connection/server, to EZ Comm,
	//	or, a connection ends, from EZ Comm
	FlowChnEnd
	// FlowChnDie is not used by EZ Comm
	FlowChnDie
	// FlowChnSnd is to send sth, to EZ Comm
	//	or, sth is sent, from EZ Comm
	FlowChnSnd
	// FlowChnSndFil is FlowChnSnd for files
	FlowChnSndFil
	// FlowChnSnt is not used by EZ Comm
	FlowChnSnt
	// FlowChnRcv is sth received, from EZ Comm
	FlowChnRcv
	// FlowChnRcvFil is FlowChnRcv for files, not used by EZ Comm. For flow only, currently
	FlowChnRcvFil
)
View Source
const (
	// HTTPSvrHTMLContentType ContentType of HTML for HTTPSvr
	HTTPSvrHTMLContentType = "text/html; charset=utf-8"
	// HTTPSvrBodyString string as body for HTTPSvr
	HTTPSvrBodyString = iota
	// HTTPSvrBodyHTML html as body for HTTPSvr
	// this is same as HTTPSvrBodyString,
	// in addition, it sets ContentType to HTTPSvrHTMLContentType
	HTTPSvrBodyHTML
	// HTTPSvrBodyJSON json as body for HTTPSvr
	HTTPSvrBodyJSON
)
View Source
const (

	// TstHalo beginning string
	TstHalo = "bonjour"
	// TstBye ending string
	TstBye = "ciao"
)

Variables

View Source
var (
	// Ver = verison
	Ver string
	// Bld = build, a number or date
	Bld string
	// Vendor & AdditionalCfgPath are to locate config file {EzcName}.xml under
	// {system-app-local-dir}/{Vendor}/{EzcName}/{AdditionalCfgPath}
	// it may vary among GUI's
	Vendor string
	// AdditionalCfgPath is to locate config file. Refer to Vendor
	AdditionalCfgPath string
)
View Source
var (
	// StringTran maps StringIndx to resource
	StringTran map[string]string
	// StringIndx is key to StringTran
	StringIndx = [...]string{
		"StrURLReadMe",
		"StrEzcName",
		"StrEzpName",
		"StrInt",
		"StrFil",
		"StrDir",
		"StrFilO",
		"StrCfg",
		"StrLcl",
		"StrRmt",
		"StrLst",
		"StrLstFl",
		"StrDis",
		"StrStp",
		"StrCon",
		"StrAdr",
		"StrPrt",
		"StrRec",
		"StrCnt",
		"StrSnd",
		"StrTo",
		"StrFrm",
		"StrFlw",
		"StrStb",
		"StrAll",
		"StrLogExp",
		"StrLang",
		"StrVbs",
		"StrHgh",
		"StrMdm",
		"StrLow",
		"StrNon",
		"StrFnt",
		"StrFnt4Lang",
		"StrFnt4LangBuiltin",
		"StrReboot4Change",
		"StrFntRch",
		"StrVer",
		"StrHlp",
		"StrV",
		"StrVV",
		"StrVVV",
		"StrLogFn",
		"StrCfgFn",
		"StrFlowFnInf",
		"StrFlowOpenErr",
		"StrFlowOpenNot",
		"StrFlowRunning",
		"StrFlowRunNot",
		"StrOK",
		"StrNG",
		"StrFlowFinAs",
		"StrCut",
		"StrCpy",
		"StrPst",
		"StrCpyAll",
		"StrClr",
		"StrListeningOn",
		"StrConnFail",
		"StrConnected",
		"StrDisconnected",
		"StrNotInRec",
		"StrSvrIdle",
		"StrClntLft",
		"StrNoPeer4",
		"StrDisconnecting",
		"StrStopLstn",
		"StrFl2Rcv",
		"StrGotFromSw",
		"StrGotFrom",
		"StrUnknownDsc",
		"StrFl2Snd",
		"StrSw",
		"StrSnt2",
		"StrInfLog",
		"StrAntiFld",
		"StrLmt",
		"StrPrd",
		"StrTooLarge2Rcv",
		"StrFileAwareness",
		"StrFileSave",
		"StrInfLan",
		"StrPokePeer",
		"StrDiscoverFail",
		"StrAlert",
		"StrNoPerm",
		"StrRcvFil",
		"StrDownloads",
		"StrExp",
		"StrRmAll",
		"StrDel",
		"StrCopied",
		"StrHeader",
		"StrValue",
		"StrSE2Del",
		"StrTxt2ShareBtCS",
		"StrLanHint",
	}
)
View Source
var (
	// TstProt protocol for tests
	TstProt *string
	// TstLcl local socket for tests
	TstLcl *string
	// TstRmt remote socket for tests
	TstRmt *string
	// TstMsg messages for tests
	TstMsg *string
	// TstRoot root dir for tests
	TstRoot *string
	// TstClntNo number of clients for tests
	TstClntNo *int
	// TstMsgCount number of messages for tests
	TstMsgCount *int
	// TstTimeout number of seconds as timeout for tests
	TstTimeout *int
	// TstTO timeout duration for tests
	TstTO time.Duration
	// TstT direct pointer to tests. better not to be used
	TstT *testing.T
)
View Source
var (
	// AntiFlood is the limit of traffic from a peer
	AntiFlood struct {
		// Limit is for incoming traffic per second.
		// negative values means limitless.
		// 0=any incoming traffic causes disconnection
		Limit int64
		// Period is to disconnect the peer immediatelyi,
		// if it connects again since previous flood.
		// non-positive values means forever.
		Period int64
		// contains filtered or unexported fields
	}
)
View Source
var (
	// CfgStruc config structure
	CfgStruc ezcommCfg
)
View Source
var FlowReaderNew func(string) (io.ReadCloser, error)

FlowReaderNew creation of a reader

View Source
var FlowWriterNew func(string) (io.WriteCloser, error)

FlowWriterNew creation of a writer

Functions

func BulkFile

func BulkFile(dir, affix string, data []byte) (fn string,
	first bool, cont []byte, end bool)

BulkFile parses data into meaningful parts IsDataFile() must be called beforehand to ensure min length

func Client

func Client(logFunc FuncLog, connFunc FuncConn,
	network, rmtAddr string,
	lstnFunc func(logFunc FuncLog, connFunc FuncConn,
		conn net.Conn, rmtAddr [2]string)) (
	conn net.Conn, err error)

Client is mainly for TCP and Unix(not -gram). It ends immediately.

lstnFunc() needs to handle procedures afterwards.
returned conn needs to Close() by user.

UDP, IP and Unixgram will be tricky to track peer information,

and preferrably use Listen*()

func Connected1Peer

func Connected1Peer(logFunc FuncLog, connFunc FuncConn,
	conn net.Conn, addrReq [2]string)

Connected1Peer works for TCP and UDP, when remote does not change Parameters:

logFunc for logging
connFunc is callback function upon entrance of this function.
  It blocks the routine.
  If flood detected, it is called with local and remote addresses,
  requested protocol and address, and nil channels
  eztools.ErrAccess is sent to chan[1].
  Network failure after the socket is closed cannot be matched,
  if not net.ErrClosed or io.EOF,
  so it is sent to chan[1] directly.
conn is the connection
addrReq is address user requested, and varies between local/remote,
  when user creates a server (listen) or a client
 -> caller: connFunc(), FlowChnRcv, FlowChnSnd, FlowChnEnd
 <- caller: FlowChnSnd, FlowChnEnd // this may block routine from exiting,
            if too much incoming traffic not read

func ConnectedUDP

func ConnectedUDP(logFunc FuncLog, chn [2]chan RoutCommStruc, conn *net.UDPConn)

ConnectedUDP works for UDP, when remote can change

It blocks.

chn[1] -> caller: FlowChnRcv, FlowChnSnd, FlowChnEnd chn[0] <- caller: FlowChnSnd, FlowChnEnd

func CurrTime

func CurrTime() string

CurrTime get time in yyyymmdd-hhmmss

func DefLanPrt

func DefLanPrt() (ret int)

DefLanPrt returns default port for lan discovery

func Deinit4Tests

func Deinit4Tests()

Deinit4Tests to use between multiple tests matching Init4Tests

func GetAvailFileName

func GetAvailFileName(fn, addr string) (string, bool)

GetAvailFileName returns fn, if not exists, or, fn_addr_ with time appended If both exist, append it with a number in addition. Return values: file name and whether an available name found

func I18nInit

func I18nInit()

I18nInit inits resource

func I18nLoad

func I18nLoad(lang string) (string, error)

I18nLoad loads a language Parameter: name of the language, as a param of eztools.AddLanguage.

It should be locale.

Return values: input language, or detected one if no param input.

func Init4Tests

func Init4Tests(t *testing.T)

Init4Tests parse flags, that are introduced from InitFlags4Tests() included in init()

func InitFlags4Tests

func InitFlags4Tests()

InitFlags4Tests needs to be included in init() from a test file, to be parsed in Init4Tests() prot: protocol, tcp, tcp4, tcp6, unix or unixpacket lcl: local address rmt: remote address msg: messages to send root: root dir for http server timeout: in seconds verbose: verbose level msgCount: number of messages to send per client for TestSvrCln quan: quantity of clients

func IsDataFile

func IsDataFile(data []byte) (isData, isEnd bool)

IsDataFile checks whether received data a file (piece) It does not guarantee successful parsing into meaningful parts.

func ListSystemFonts

func ListSystemFonts(exts []string) []string

ListSystemFonts get all system fonts with extensions

func ListenIP

func ListenIP(network, address string) (*net.IPConn, error)

ListenIP listens to IP. It ends immediately. Parameters:

network is socket type, "ip", "ip4" or "ip6"
address is for local, [IP or DN][:protocol number or name]

func ListenTCP

func ListenTCP(logFunc FuncLog, connFunc FuncConn,
	network, address string, accepted func(FuncLog,
		FuncConn, net.Conn, [2]string), errChan chan error) (
	net.Listener, error)

ListenTCP listens to TCP. It ends immediately. Simply close the listener to stop it.

Parameters:
network is socket type, "tcp", "tcp4" or "tcp6"
accepted() needs to handle procedures for incoming connections.
  can be nil.
  It blocks listening routine, so that errChan gets feedback
  always before accepted().
connFunc is for accepted() only.
errChan sends Accept errors

func ListenUDP

func ListenUDP(network, address string) (*net.UDPConn, error)

ListenUDP listens to UDP. It ends immediately.

*net.UDPConn needs to handle procedures afterwards.

Parameters:

network is socket type, "udp", "udp4" or "udp6"
address is for local, [IP or DN][:port number or name]

func ListenUnixgram

func ListenUnixgram(network, address string) (*net.UnixConn, error)

ListenUnixgram listens to unixgram. It ends immediately. Parameters:

network is socket type, "unixgram"
address is for local, [IP or DN][:port number or name]

func MatchFontFromCurrLanguageCfg

func MatchFontFromCurrLanguageCfg()

MatchFontFromCurrLanguageCfg matches font for current language in config

func MatchSystemFontsFromIndex

func MatchSystemFontsFromIndex(indx int) string

MatchSystemFontsFromIndex returns font path from index into fontList[0 or 1]

func MatchSystemFontsFromPath

func MatchSystemFontsFromPath(str string) int

MatchSystemFontsFromPath is reverse function for matchSystemFontsFromIndex Return value: eztools.InvalidID if not found

func MdnsClient

func MdnsClient(localName string, chnAddr chan netip.Addr,
	chnStp chan struct{}, chnErr chan error, timeout time.Duration)

MdnsClient creats a client and queries Parameters: localName must match server channels can be nil

func MdnsServer

func MdnsServer(localName string, chnStp chan struct{},
	chnErr chan error) (server *mdns.Conn, err error)

MdnsServer creats a server and waits for queries Parameters: chnErr can be nil, others must not Return values: not to be used, except for internal MdnsClient for internal usage, when localName is empty and chnStp is nil, server does not wait and is for MdnsClient.

func ReadCfg

func ReadCfg(cfg string, fallbackLang string) error

ReadCfg reads config from a file

func ReaderCfg

func ReaderCfg(rdr io.ReadCloser, fallbackLang string) error

ReaderCfg reads config from a Reader Closer is closed before returning

func RunFlow

func RunFlow(flow FlowStruc) bool

RunFlow runs a read flow structure Return value: whether succeeded

func SetLog

func SetLog(fil string, wr io.Writer) (err error)

SetLog sets a writer or file as log date and time will be prefixed to the file; none to a writer, otherwise.

func SndFile

func SndFile(fn string, rdr io.ReadCloser, proc func([]byte) error) error

SndFile sends a file without splitting. Parameter: rdr is closed before returning Return value:

ErrOutOfBound if file+prefix larger than FlowRcvLen
other error from os.Stat(), ioutil.ReadFile(), or prefix4File()
value from proc()

func SplitFile

func SplitFile(fn string, rdr io.ReadCloser, proc func([]byte) error) error

SplitFile splits a file Parameter: rdr is closed before returning

func Sz41stChunk

func Sz41stChunk(fnI string) (int, string)

Sz41stChunk returns max data size to transfer in first chunk

if input file name is too long, a valid one is returned

func TryOnlyChunk

func TryOnlyChunk(fnI string, rdr io.ReadCloser) (string, []byte, error)

TryOnlyChunk try to read the file in one chunk Parameter: rdr is closed before returning Return values:

a possible long file name
read buffer
ErrOutOfBound if no valid data fits
ErrInvalidInput file larger than one chunk

func WriteCfg

func WriteCfg() error

WriteCfg to save config

func WriterCfg

func WriterCfg(wrt io.WriteCloser) error

WriterCfg to save config using Writer Closer is closed before returning

Types

type FlowConnStruc

type FlowConnStruc struct {
	// Cmt = comments
	Cmt string `xml:",comment"`
	// Txt is not used
	Txt string `xml:",chardata"`

	Name     string `xml:"name,attr"`
	Protocol string `xml:"protocol,attr"`
	Addr     string `xml:"address,attr"`
	Peer     string `xml:"peer,attr"`
	Block    bool   `xml:"block,attr"`
	// TODO: use Wait?
	Wait  string          `xml:"wait,attr"`
	Steps []FlowStepStruc `xml:"step"`
	// contains filtered or unexported fields
}

FlowConnStruc a connection in a flow

func (*FlowConnStruc) Connected

func (conn *FlowConnStruc) Connected(logFunc FuncLog,
	connFunc FuncConn, connTCP net.Conn, addr [2]string)

Connected when connected in flow

func (*FlowConnStruc) LockLog

func (conn *FlowConnStruc) LockLog(nm string, lck bool)

LockLog un-/locks for log

func (*FlowConnStruc) ParsePeer

func (conn *FlowConnStruc) ParsePeer(flow FlowStruc)

ParsePeer parses peer in struct

func (*FlowConnStruc) Run

func (conn *FlowConnStruc) Run(flow *FlowStruc)

Run runs a flow to be run by RunFlow, b/c no (de-)init for channels

func (*FlowConnStruc) RunCln

func (conn *FlowConnStruc) RunCln(flow FlowStruc)

RunCln runs a client to be run by FlowConnStruc.Run(), b/c no (de-)init for channels

func (*FlowConnStruc) RunSvr

func (conn *FlowConnStruc) RunSvr(flow FlowStruc)

RunSvr supports TCP & UDP only. TODO: IP & Unix to be run by FlowConnStruc.Run(), b/c no (de-)init for channels

func (FlowConnStruc) Step1

func (conn FlowConnStruc) Step1(flow *FlowStruc, step *FlowStepStruc)

Step1 runs 1 step in flow

func (FlowConnStruc) StepAll

func (conn FlowConnStruc) StepAll(flow *FlowStruc, steps []FlowStepStruc)

StepAll runs steps in flow

func (*FlowConnStruc) Wait4

func (conn *FlowConnStruc) Wait4(flow FlowStruc) (ret string)

Wait4 waits for chan from server

type FlowStepStruc

type FlowStepStruc struct {
	// Cmt = comments
	Cmt string `xml:",comment"`
	// Txt is not used
	Txt string `xml:",chardata"`

	Act string `xml:"action,attr"`
	// Name if not null, this structure will be mapped to Vals
	Name string `xml:"name,attr"`
	// Dest will be updated upon UDP receive action, if it is a variable
	Dest string `xml:"dest,attr"`
	Data string `xml:"data,attr"`
	// Loop rounds to repeat this step
	// 0, 1: no loop
	// > 1: number of rounds
	// < 0: infinitely
	Loop  int  `xml:"loop,attr"`
	Block bool `xml:"block,attr"`
	// Steps: sub steps triggered
	Steps []FlowStepStruc `xml:"step"`
}

FlowStepStruc a step in a flow

func (FlowStepStruc) ParseData

func (step FlowStepStruc) ParseData(flow FlowStruc,
	conn FlowConnStruc) (string, int)

ParseData parses data in step Return values:

	1st. is one of following
	  data string in form of a simple string
	  data string where substituted if possible, the value of a member of FlowConnStruc or FlowStepStruc for <string> in <FlowVarSign><xml tag name of FlowConnStruc or FlowStepStruc><FlowVarSep><string><FlowVarSign>
	  file name for <string> in <FlowVarSign><FlowVarFil><FlowVarSep><string><FlowVarSign>
	2nd.
	 0: a string
	 1(=difference from FlowChnRcv to FlowChnRcvFil): a file name
         2: a script name

func (FlowStepStruc) ParseDest

func (step FlowStepStruc) ParseDest(flow FlowStruc,
	conn FlowConnStruc) *net.UDPAddr

ParseDest parses destination in flow

type FlowStruc

type FlowStruc struct {
	// Root of the XML
	Root xml.Name `xml:"ezcommFlow"`
	// Cmt = comments
	Cmt string `xml:",comment"`
	// Txt is not used
	Txt   string          `xml:",chardata"`
	Conns []FlowConnStruc `xml:"conn"`
	Vals  map[string]*FlowStepStruc
}

FlowStruc defines the structure of a flow xml

func ReadFlowFile

func ReadFlowFile(file string) (flow FlowStruc, err error)

ReadFlowFile reads flow from a file

func ReadFlowReader

func ReadFlowReader(rdr io.ReadCloser) (flow FlowStruc, err error)

ReadFlowReader reads flow from a reader

func (FlowStruc) ParseVar

func (flow FlowStruc) ParseVar(str string,
	fun func(int, string)) (string, int)

ParseVar parses a string of a simple string or

  <FlowVarSign>[<xml tag name of FlowConnStruc/FlowStepStruc><FlowVarSign>]<string><FlowVarSign>
  fun() is invoked for matched FlowConnStruc,
	with index of it in FlowStruc.Conns and <string>

Return values:

1st.
 If FlowConnStruc is matched, the value of its member whose xml tag is <string>
 Otherwise, the input <string>
2nd. FlowParseVal*, that's to say, FlowParseValSimple, FlowParseValSign, or FlowParseValVar

type Fonts

type Fonts struct {
	// Cmt is not used
	Cmt string `xml:",comment"`
	// Locale is like zh-TW
	Locale string `xml:"locale,attr"`
	// Font is built-in names for fonts, which are locales,
	// or paths of fonts
	Font string `xml:"font,attr"`
}

Fonts is a font-locale match

type FuncConn

type FuncConn func(addr [4]string, chn [2]chan RoutCommStruc)

FuncConn is run when Connected. addr=address info.

[0]: parsed local
[1]: remote
[2]: requested protocol
[3]: requested address

close(chan[...]) upon exiting!

[0]: to ezcomm
[1]: from ezcomm

type FuncLog

type FuncLog func(...any)

FuncLog is log function

type HTTPSvr

type HTTPSvr struct {
	// contains filtered or unexported fields
}

HTTPSvr Serv=serve Shut=shutdown

func MakeHTTPSvr

func MakeHTTPSvr() *HTTPSvr

MakeHTTPSvr makes a HTTPSvr

func (*HTTPSvr) FS

func (svr *HTTPSvr) FS(relativePath, rootPath string, fs http.FileSystem)

FS sets a static file system Parameters: fs OR rootPath: to use a filesystem or gin's default

func (*HTTPSvr) GET

func (svr *HTTPSvr) GET(relativePath string, fun HTTPSvrProcFunc)

GET sets a GET handler

func (*HTTPSvr) POST

func (svr *HTTPSvr) POST(relativePath string, fun HTTPSvrProcFunc)

POST shows a text input

func (*HTTPSvr) Serve

func (svr *HTTPSvr) Serve(lst net.Listener) chan error

Serve http.Serve with handler set by FS() Return value: error from http.Serve()

func (*HTTPSvr) Shutdown

func (svr *HTTPSvr) Shutdown(timeout time.Duration) error

Shutdown gracefully shuts down the server Return value: context.DeadlineExceeded if timeout

type HTTPSvrBody

type HTTPSvrBody struct {
	// Tp type, one of HTTPSvrBodyString, HTTPSvrBodyHTML
	// and HTTPSvrBodyJSON
	Tp int
	// Str for HTTPSvrBodyString and HTTPSvrBodyHTML
	Str string
	// JSON for HTTPSvrBodyJSON, map[string]any
	JSON gin.H
}

HTTPSvrBody body for HTTPSvr

type HTTPSvrProcFunc

type HTTPSvrProcFunc func(string, *http.Request,
	func(string) string) (int, HTTPSvrBody, map[string]string)

HTTPSvrProcFunc method proc func type for HTTPSvr

Parameters:

remote IP request func to get values by keys

Return values:
response code, body, headers. 204 is default if fun is nil.

type RoutCommStruc

type RoutCommStruc struct {
	// ReqAddr is address from user
	ReqAddr string
	// Act action
	Act int
	// PeerUDP is filled, and required for FlowChnSnd by EZ Comm
	PeerUDP *net.UDPAddr
	// PeerTCP is filled, but not required by EZ Comm
	PeerTCP net.Addr
	// Data is I/O raw message
	Data []byte
	// Resp for SvrTcp and flow only
	Resp chan RoutCommStruc
	Err  error
}

RoutCommStruc is communication struct between EZComm and user

type SvrTCP

type SvrTCP struct {

	// LogFunc is not routine safe, for logging
	// behavior undefined if not set
	LogFunc FuncLog
	// ActFunc is for FlowChnRcv, FlowChnEnd, FlowChnSnd to user.
	// behavior undefined if not set
	ActFunc func(RoutCommStruc)
	// ConnFunc runs upon an incoming connection
	//   It must not block
	// also runs on listening, to tell user of the actual address
	// behavior undefined if not set
	ConnFunc func([4]string)
	// contains filtered or unexported fields
}

SvrTCP handles all clients and uses requested address to match them with user

routines
             SvrTCP  |  ezcomm
             ======= | =======

listening (Connected) | connected:* ListenTcp ConnectedTcp:2 ===================== | ===================================

|-----------------------------------|

    1 incoming connection           |-------------->
            <-----[2]channel, ezcomm------------|
<-channel[0]|channel[1]->

            incoming traffic
<-----chnLstn-----------|<-channel[1], ezcomm---|

ChnConn[1]

            outgoing traffic
|------------------channel[0], ezcomm---------->|

ChnConn[0]

|----------break 1 connection------------------>^

ChnConn[0]

<----------1 connection broken-----------------^

ChnConn[1]

|--break 1 connection ->^

|close listener

ChnConn[0]

  listening stopped, sending chnSvr^

^ (listening stopped and no connections in existence)

ChnConn[1]

func (*SvrTCP) Disconnect

func (s *SvrTCP) Disconnect(addr string)

Disconnect disconnects a/all connection(-s)

routine safe

func (*SvrTCP) HasStopped

func (s *SvrTCP) HasStopped() bool

HasStopped whether SvrTCP has Stop-ped

func (*SvrTCP) Listen

func (s *SvrTCP) Listen(network, addr string) (err error)

Listen returns whether successfully listening ConnFunc is called before returning, with only listening address as the first member of the slice. ConnFunc may be called after a client incomes and is reported because of routine schedules.

func (*SvrTCP) Send

func (s *SvrTCP) Send(addr string, data []byte)

Send is routine safe

act should be FlowChnSnd

func (*SvrTCP) Stop

func (s *SvrTCP) Stop()

Stop stops listening

routine safe, except with Listen()

func (*SvrTCP) Wait

func (s *SvrTCP) Wait(clients bool)

Wait returns when server/all clients stopped

user needs to run Disconnect() whatsever

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL