go_dreamfactory/cmd/v2/ui/tool_ping.go
2023-01-05 15:50:12 +08:00

77 lines
1.6 KiB
Go

package ui
import (
"fmt"
"go_dreamfactory/cmd/v2/lib/common"
"go_dreamfactory/cmd/v2/service"
"go_dreamfactory/cmd/v2/service/observer"
"net"
"strings"
"sync"
"time"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/theme"
"fyne.io/fyne/v2/widget"
"github.com/spf13/cast"
)
type appPing struct {
appAdapter
resultCh chan int
}
func (this *appPing) LazyInit(ptService service.PttService, obs observer.Observer) error {
this.tabItem = container.NewTabItemWithIcon(common.TOOLBAR_PING, theme.DownloadIcon(), nil)
this.resultCh = make(chan int)
content := container.NewMax()
content.Objects = []fyne.CanvasObject{}
targetHost := widget.NewEntry()
targetHost.PlaceHolder = "目标主机Ip"
portEntry := widget.NewMultiLineEntry()
portEntry.Text = "80,3306,6379"
form := widget.NewForm(
widget.NewFormItem("端口", portEntry),
)
form.OnSubmit = func() {
ports := strings.Split(portEntry.Text, ",")
this.ping(targetHost.Text, ports)
for p := range this.resultCh {
fmt.Println(p, "ok")
}
}
form.Items[1].HintText = "多个端口使用英文,号分隔"
content.Objects = append(content.Objects, form)
this.tabItem.Content = content
return nil
}
func (this *appPing) ping(targetHost string, ports []string) {
var wg sync.WaitGroup
wg.Add(len(ports))
for _, port := range ports {
go func(p int) {
defer wg.Done()
_, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", targetHost, p), time.Millisecond*500)
if err == nil {
this.resultCh <- p
}
}(cast.ToInt(port))
}
go func() {
defer close(this.resultCh)
wg.Wait()
}()
}
func (a *appPing) GetAppName() string {
return common.TOOLBAR_PING
}