diff --git a/deeplink_windows.go b/deeplink_windows.go index 6381d68..518bf44 100644 --- a/deeplink_windows.go +++ b/deeplink_windows.go @@ -97,45 +97,54 @@ func (dl *DeepLink) Unregister() (bool, error) { } -// Prepare prepares the DeepLink instance for receiving messages, this is required to redirect message to already running app -func (dl *DeepLink) Prepare() { - go func() { - listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", dl.Port)) - if err != nil { - if strings.Contains(err.Error(), "Only one usage of each socket address") { - conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", dl.Port)) - if err != nil { - os.Exit(1) - } +func isAnotherProcessExists(port uint) bool { + conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port)) + if err != nil { + return false + } - conn.Write([]byte(os.Args[len(os.Args)-1])) - conn.Close() + conn.Close() - os.Exit(0) - } - } + return true +} - // listen for incoming connections - for { - message, err := listener.Accept() - if err != nil { - os.Exit(0) - } +func (dl *DeepLink) listen(port uint) { + listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port)) + if err != nil { + log.Fatal(err) + } + for { + conn, err := listener.Accept() + if err != nil { + log.Fatal(err) + } + + go func() { buf := make([]byte, 1024) - n, err := message.Read(buf) - if err != nil { - os.Exit(0) - } + n, _ := conn.Read(buf) - var msg string if n > 0 { - msg = string(buf[:n]) + dl.OnMessage(string(buf[:n])) + } + }() + } +} - if dl.OnMessage != nil { - dl.OnMessage(msg) - } +// Prepare prepares the DeepLink instance for receiving messages, this is required to redirect message to already running app +func (dl *DeepLink) Prepare() { + go func() { + if isAnotherProcessExists(dl.Port) { + conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", dl.Port)) + if err != nil { + log.Fatal(err) } + + conn.Write([]byte(os.Args[len(os.Args)-1])) + conn.Close() + os.Exit(0) + } else { + dl.listen(dl.Port) } }() } diff --git a/test/main.go b/test/main.go new file mode 100644 index 0000000..38ddf20 --- /dev/null +++ b/test/main.go @@ -0,0 +1,14 @@ +package main + +import "github.com/kaazedev/deeplink" + +func main() { + dl := deeplink.NewDeeplink("resourcer", 8080) + dl.Prepare() + dl.Register(func(message string) { + println("Message received: " + message) + }) + + for { + } +}