diff --git a/dial/dial_dial_test.go b/dial/dial_dial_test.go index aa044e8..53a5ad2 100644 --- a/dial/dial_dial_test.go +++ b/dial/dial_dial_test.go @@ -23,6 +23,22 @@ func TestRedialWebsocket(t *testing.T) { <-c.DoneAll() } +func TestRedialWebsocket2(t *testing.T) { + url := "ws://127.0.0.1/api/user/notice/ws" + //"ws://192.168.10.3:1880/node-red/comms" + //url = "ws://192.168.10.24:10001/api/ai/info/runtime/ws?id=83" + //url = "ws://192.168.10.38:80/api/ai/photo/ws?key=0.0" + //url := "ws://192.168.10.24:10001/api/user/notice/ws" + //url += "?token=jbYKl72cbOGvbVRwIqM4r6eoirw8f1JRD44+4D5E/URRY4L6TTZYYb/9yhedvd2Ii2GtLo9MieBy5FBeUhugK5jHvppFjExz3B5DVFPqsomF5wezKDFc8a2hZSQ9IDHTS/C+j/3ESSRdbkVHPFxbzQ==" + //url = strings.ReplaceAll(url, "+", "%2B") + logs.Debug(url) + c := RedialWebsocket(url, nil, func(c *io.Client) { + c.Debug() + //c.GoTimerWriteASCII(time.Second, "666") + }) + <-c.DoneAll() +} + func TestRedialTCP(t *testing.T) { //"ws://192.168.10.3:1880/node-red/comms" RedialTCP(":1082", func(c *io.Client) { diff --git a/dial/dial_serial_test.go b/dial/dial_serial_test.go index 00c731d..0215542 100644 --- a/dial/dial_serial_test.go +++ b/dial/dial_serial_test.go @@ -24,9 +24,9 @@ func TestNewSerial(t *testing.T) { } defer c.Close() c.Debug() - c.SetPrintFunc(func(msg io.Message, tag ...string) { - logs.Debug(tag, msg) - }) + //c.SetPrintFunc(func(msg io.Message, tag ...string) { + // logs.Debug(tag, msg) + //}) c.SetReadWithAll() t.Log(c.Run()) @@ -44,9 +44,9 @@ func TestNewSerial2(t *testing.T) { } defer c.Close() c.Debug() - c.SetPrintFunc(func(msg io.Message, tag ...string) { - logs.Debug(tag, msg) - }) + //c.SetPrintFunc(func(msg io.Message, tag ...string) { + // logs.Debug(tag, msg) + //}) c.SetReadWithAll() go c.Run() diff --git a/dial/proxy/proxy_server.go b/dial/proxy/proxy_server.go index acc38af..fe9e0d0 100644 --- a/dial/proxy/proxy_server.go +++ b/dial/proxy/proxy_server.go @@ -6,7 +6,7 @@ import ( "errors" "fmt" "github.com/injoyai/io" - "github.com/injoyai/io/dial" + "github.com/injoyai/io/listen" "github.com/injoyai/logs" "net/http" "net/url" @@ -89,7 +89,7 @@ func NewServer(dial io.ListenFunc, options ...func(s *Server)) (*Server, error) //}) ser = &Server{s: s, e: New(), dealFunc: func(msg *CMessage) error { m := "未设置处理函数" - io.Log.Errorf("[PR|S] 未设置处理函数") + s.Logger.Errorf("[PR|S] 未设置处理函数") //s.Print([]byte("未设置处理函数"), "PR|S", io.TagErr) return errors.New(m) }} @@ -148,7 +148,7 @@ func NewServer(dial io.ListenFunc, options ...func(s *Server)) (*Server, error) } func NewUDPServer(port int, options ...func(s *Server)) (*Server, error) { - s, err := NewServer(dial.UDPListenFunc(port), options...) + s, err := NewServer(listen.UDPListenFunc(port), options...) if err == nil { s.s.SetKey(fmt.Sprintf(":%d", port)) } @@ -156,7 +156,7 @@ func NewUDPServer(port int, options ...func(s *Server)) (*Server, error) { } func NewTCPServer(port int, options ...func(s *Server)) (*Server, error) { - s, err := NewServer(dial.TCPListenFunc(port), options...) + s, err := NewServer(listen.TCPListenFunc(port), options...) if err == nil { s.s.SetKey(fmt.Sprintf(":%d", port)) } diff --git a/io_client.go b/io_client.go index 498b0ce..ec8b3f2 100644 --- a/io_client.go +++ b/io_client.go @@ -271,13 +271,11 @@ func (this *Client) Redial(options ...OptionClient) *Client { readWriteCloser := this.IReadCloser.MustDial(ctx) if readWriteCloser == nil { if this.ICloser.Err() != ErrHandClose { - Log.Errorf("[%s] 连接断开(%v),未设置重连函数", this.GetKey(), this.ICloser.Err()) - //this.ICloser.Print(NewMessageFormat("连接断开(%v),未设置重连函数", this.ICloser.Err()), TagErr, this.GetKey()) + this.Logger.Errorf("[%s] 连接断开(%v),未设置重连函数", this.GetKey(), this.ICloser.Err()) } return } - Log.Infof("[%s] 连接断开(%v),重连成功", this.GetKey(), this.ICloser.Err()) - //this.ICloser.Print(NewMessageFormat("连接断开(%v),重连成功", this.ICloser.Err()), TagInfo, this.GetKey()) + this.Logger.Infof("[%s] 连接断开(%v),重连成功", this.GetKey(), this.ICloser.Err()) redialFunc := this.IReadCloser.redialFunc key := this.GetKey() *this = *NewClient(readWriteCloser) @@ -288,8 +286,7 @@ func (this *Client) Redial(options ...OptionClient) *Client { }) this.SetOptions(options...) //新建客户端时已经能确定连接成功,为了让用户控制是否输出,所以在Run的时候打印 - Log.Infof("[%s] 连接服务端成功...", this.GetKey()) - //this.Print(Message("连接服务端成功..."), TagInfo, this.GetKey()) + this.Logger.Infof("[%s] 连接服务端成功...", this.GetKey()) go this.Run() return this } diff --git a/io_client_manage.go b/io_client_manage.go index a23450e..fb02c8a 100644 --- a/io_client_manage.go +++ b/io_client_manage.go @@ -73,6 +73,7 @@ type ClientManage struct { timeout time.Duration //超时时间,小于0是不超时 timeoutInterval time.Duration //超时检测间隔 + Logger ILog *printer } @@ -209,7 +210,7 @@ func (this *ClientManage) SetClient(c *Client) { //前置操作,例如等待注册数据,不符合的返回错误则关闭连接 if this.beforeFunc != nil { if err := this.beforeFunc(c); err != nil { - Log.Errorf("[%s] %v", c.GetKey(), err) + this.Logger.Errorf("[%s] %v", c.GetKey(), err) //this.Print(Message(err.Error()), TagErr) _ = c.Close() return diff --git a/io_config.go b/io_config.go index 0b84917..14032e1 100644 --- a/io_config.go +++ b/io_config.go @@ -3,12 +3,4 @@ package io var ( // DealErr 错误处理配置 DealErr = defaultDealErr - - // Log 日志配置 - Log ILog = &_log{} ) - -func Default() { - DealErr = defaultDealErr - Log = &_log{} -} diff --git a/io_i_closer.go b/io_i_closer.go index d21093e..e52a0fa 100644 --- a/io_i_closer.go +++ b/io_i_closer.go @@ -15,7 +15,8 @@ func NewICloserWithContext(ctx context.Context, closer Closer) *ICloser { ctxParent, cancelParent := context.WithCancel(ctx) ctx, cancel := context.WithCancel(ctxParent) return &ICloser{ - printer: newPrinter(""), + Logger: newLog(), + //printer: newPrinter(""), closer: closer, redialFunc: nil, redialMaxTime: time.Second * 32, @@ -30,7 +31,9 @@ func NewICloserWithContext(ctx context.Context, closer Closer) *ICloser { } type ICloser struct { - *printer //打印 + Logger + key + //*printer //打印 closer Closer //实例 redialFunc DialFunc //重连函数 redialMaxTime time.Duration //最大尝试退避重连时间 @@ -233,7 +236,7 @@ func (this *ICloser) closeWithErr(closeErr error, fn ...func(Closer) error) (err //生成错误信息 msg := Message(this.closeErr.Error()) //打印错误信息 - Log.Errorf("[%s] %s", this.GetKey(), msg) + this.Logger.Errorf("[%s] %s", this.GetKey(), msg) //this.printer.Print(msg, TagErr, this.GetKey()) //执行用户设置的错误函数 if this.closeFunc != nil { @@ -267,7 +270,7 @@ func (this *ICloser) MustDial(ctx context.Context) ReadWriteCloser { if t > this.redialMaxTime { t = this.redialMaxTime } - Log.Errorf("[%s] %v,等待%d秒重试", this.GetKey(), dealErr(err), t/time.Second) + this.Logger.Errorf("[%s] %v,等待%d秒重试", this.GetKey(), dealErr(err), t/time.Second) //this.Print(NewMessageFormat("%v,等待%d秒重试", dealErr(err), t/time.Second), TagErr, this.GetKey()) timer.Reset(t) } diff --git a/io_i_printer.go b/io_i_printer.go index 941758c..89b7141 100644 --- a/io_i_printer.go +++ b/io_i_printer.go @@ -3,10 +3,28 @@ package io import ( "fmt" "io" - "log" "strings" ) +type key string + +func (this *key) GetKey() string { + return string(*this) +} + +func (this *key) SetKey(s string) { + *this = key(s) +} + +type coding string + +func (this *coding) SetPrintWithHEX() { + *this = "hex" +} + +func (this *coding) SetPrintWithASCII() { + *this = "ascii" +} func newPrinter(key string) *printer { cp := &printer{} cp.SetKey(key) @@ -35,11 +53,6 @@ func (this *printer) SetPrintFunc(fn PrintFunc) { this.printFunc = fn } -//// GetPrintFunc 获取打印函数 -//func (this *printer) GetPrintFunc() PrintFunc { -// return this.printFunc -//} - // SetPrintWithHEX 设置打印HEX func (this *printer) SetPrintWithHEX() { this.SetPrintFunc(PrintWithHEX) @@ -82,23 +95,23 @@ func (this *printer) GetDebug() bool { //================================Common================================ func PrintWithHEX(msg Message, tag ...string) { - log.Print(PrintfWithHEX(msg, tag...)) + //log.Print(PrintfWithHEX(msg, tag...)) } // PrintWithASCII todo [13 10 69 82 82 79 82 13 10]用log.Print打印不出来 func PrintWithASCII(msg Message, tag ...string) { - log.Print(PrintfWithASCII(msg, tag...)) + //log.Print(PrintfWithASCII(msg, tag...)) } func PrintWithBase(msg Message, tag ...string) { if len(tag) > 0 && (tag[0] == TagErr || tag[0] == TagInfo) { - log.Print(PrintfWithASCII(msg, tag...)) + //log.Print(PrintfWithASCII(msg, tag...)) } } func PrintWithErr(msg Message, tag ...string) { if len(tag) > 0 && tag[0] == TagErr && msg.String() != io.EOF.Error() { - log.Print(PrintfWithASCII(msg, tag...)) + //log.Print(PrintfWithASCII(msg, tag...)) } } diff --git a/io_i_reader.go b/io_i_reader.go index fbd3ec7..1f5a22c 100644 --- a/io_i_reader.go +++ b/io_i_reader.go @@ -11,7 +11,8 @@ import ( // NewIReader 新建IReader,默认读取函数ReadAll func NewIReader(r Reader) *IReader { i := &IReader{ - printer: newPrinter(""), + Logger: newLog(), + //printer: newPrinter(""), lastChan: make(chan Message), lastTime: time.Now(), } @@ -25,7 +26,8 @@ func NewIReader(r Reader) *IReader { } type IReader struct { - *printer //printer + Logger + //*printer //printer mReader MessageReader //接口MessageReader,兼容Reader buf *bufio.Reader //buffer readFunc ReadFunc //读取函数 @@ -122,8 +124,7 @@ func (this *IReader) SetReadFunc(fn func(*bufio.Reader) ([]byte, error)) *IReade default: } //打印日志 - Log.Readf("["+this.GetKey()+"] %s", string(bs)) - //this.Print(bs, TagRead, this.GetKey()) + this.Logger.Read(bs) } return bs, nil } diff --git a/io_i_write_closer.go b/io_i_write_closer.go index 5346fa9..3ffd457 100644 --- a/io_i_write_closer.go +++ b/io_i_write_closer.go @@ -34,12 +34,12 @@ func (this *IWriteCloser) SetKey(key string) *IWriteCloser { return this } -// SetPrintFunc 设置打印函数 -func (this *IWriteCloser) SetPrintFunc(fn PrintFunc) *IWriteCloser { - this.IWriter.SetPrintFunc(fn) - this.ICloser.SetPrintFunc(fn) //错误信息按ASCII编码? - return this -} +//// SetPrintFunc 设置打印函数 +//func (this *IWriteCloser) SetPrintFunc(fn PrintFunc) *IWriteCloser { +// this.IWriter.SetPrintFunc(fn) +// this.ICloser.SetPrintFunc(fn) //错误信息按ASCII编码? +// return this +//} func (this *IWriteCloser) Debug(b ...bool) *IWriteCloser { this.IWriter.Debug(b...) diff --git a/io_i_writer.go b/io_i_writer.go index fae2404..4ed1565 100644 --- a/io_i_writer.go +++ b/io_i_writer.go @@ -19,7 +19,8 @@ func NewIWriter(writer Writer) *IWriter { return c } return &IWriter{ - printer: newPrinter(""), + Logger: newLog(), + //printer: newPrinter(""), writer: writer, writeFunc: nil, lastTime: time.Time{}, @@ -28,11 +29,15 @@ func NewIWriter(writer Writer) *IWriter { // IWriter 写 type IWriter struct { - *printer //打印 - writer Writer //io.Writer - writeFunc WriteFunc //写入函数 - writeAfter func(p []byte, err error) //写结束后 - lastTime time.Time //最后写入时间 + Logger + key + + //*printer //打印 + writer Writer //io.Writer + writeFunc WriteFunc //写入函数 + writeAfter func(p []byte, err error) //写结束后 + lastTime time.Time //最后写入时间 + printCoding string //数据编码模式 } //================================Nature================================ @@ -56,8 +61,13 @@ func (this *IWriter) Write(p []byte) (n int, err error) { } } //打印实际发送的数据,方便调试 - Log.Writef("["+this.GetKey()+"] %s", string(p)) - //this.Print(p, TagWrite, this.GetKey()) + switch this.printCoding { + case "hex": + this.Logger.Readf("["+this.GetKey()+"] %s", hex.EncodeToString(p)) + default: + this.Logger.Readf("["+this.GetKey()+"] %s", string(p)) + } + //写入数据 n, err = this.writer.Write(p) if err != nil { return 0, dealErr(err) diff --git a/io_log.go b/io_log.go index 3ef9cfe..912051f 100644 --- a/io_log.go +++ b/io_log.go @@ -1,7 +1,8 @@ package io import ( - "log" + "encoding/hex" + golog "log" ) const ( @@ -30,45 +31,88 @@ func (this Level) String() string { return "未知" } -func (this Level) printf(level Level, format string, v ...interface{}) { - if this >= level { - log.Printf("["+this.String()+"]"+format, v...) +func (this Level) printf(log *log, format string, v ...interface{}) { + if log.debug && this >= log.level { + prefix := "[" + this.String() + "]" + if len(log.key) > 0 { + prefix += "[" + log.key + "]" + } + golog.Printf(prefix+format, v...) } } +type Logger = ILog + type ILog interface { Level(level Level) - Readf(format string, v ...interface{}) - Writef(format string, v ...interface{}) + Debug(b ...bool) + Read(p []byte) + Write(p []byte) Infof(format string, v ...interface{}) Debugf(format string, v ...interface{}) Errorf(format string, v ...interface{}) } -type _log struct { - level Level +func newLog() Logger { + return &log{ + debug: true, + coding: "ascii", + } +} + +type log struct { + level Level + key string + debug bool + coding string } -func (this *_log) Level(level Level) { +func (this *log) SetKey(key string) { + this.key = key +} + +func (this *log) Level(level Level) { this.level = level } -func (this *_log) Infof(format string, v ...interface{}) { - LevelInfo.printf(this.level, format, v...) +func (this *log) Debug(b ...bool) { + this.debug = !(len(b) > 0 && b[0]) +} + +func (this *log) SetPrintWithHEX() { + this.coding = "hex" +} + +func (this *log) SetPrintWithASCII() { + this.coding = "ascii" } -func (this *_log) Writef(format string, v ...interface{}) { - LevelWrite.printf(this.level, format, v...) +func (this *log) Write(p []byte) { + switch this.coding { + case "hex": + LevelWrite.printf(this, "%s", hex.EncodeToString(p)) + default: + LevelWrite.printf(this, "%s", string(p)) + } +} + +func (this *log) Read(p []byte) { + switch this.coding { + case "hex": + LevelRead.printf(this, "%s", hex.EncodeToString(p)) + default: + LevelRead.printf(this, "%s", string(p)) + } } -func (this *_log) Readf(format string, v ...interface{}) { - LevelRead.printf(this.level, format, v...) +func (this *log) Infof(format string, v ...interface{}) { + LevelInfo.printf(this, format, v...) } -func (this *_log) Debugf(format string, v ...interface{}) { - LevelDebug.printf(this.level, format, v...) +func (this *log) Debugf(format string, v ...interface{}) { + LevelDebug.printf(this, format, v...) } -func (this *_log) Errorf(format string, v ...interface{}) { - LevelError.printf(this.level, format, v...) +func (this *log) Errorf(format string, v ...interface{}) { + LevelError.printf(this, format, v...) } diff --git a/io_server.go b/io_server.go index e7cd860..d5e3aa9 100644 --- a/io_server.go +++ b/io_server.go @@ -28,6 +28,7 @@ func NewServerWithContext(ctx context.Context, newListen func() (Listener, error } //新建实例 s := &Server{ + Logger: &log{}, printer: newPrinter(fmt.Sprintf("%p", listener)), ICloser: NewICloserWithContext(ctx, listener), ClientManage: NewClientManage(ctx, fmt.Sprintf("%p", listener)), @@ -52,6 +53,7 @@ func NewServerWithContext(ctx context.Context, newListen func() (Listener, error // Server 服务端 type Server struct { + Logger ILog *printer *ICloser *ClientManage @@ -117,7 +119,7 @@ func (this *Server) Run() error { return nil } - Log.Infof("[%s] 开启服务成功...", this.GetKey()) + this.Logger.Infof("[%s] 开启服务成功...", this.GetKey()) //this.Print(Message("开启服务成功..."), TagInfo, this.GetKey()) //执行监听连接 @@ -136,7 +138,7 @@ func (this *Server) Run() error { //新建客户端,并配置 x := NewClientWithContext(this.Ctx(), c).SetKey(key) - Log.Infof("[%s] 新的客户端连接...", this.GetKey()) + this.Logger.Infof("[%s] 新的客户端连接...", this.GetKey()) //this.Print(Message("新的客户端连接..."), TagInfo, x.GetKey()) this.ClientManage.SetClient(x)