Skip to content

Commit

Permalink
feat: refactor some parts
Browse files Browse the repository at this point in the history
  • Loading branch information
pers0na2dev committed Sep 23, 2023
1 parent f235629 commit 75f5c09
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 30 deletions.
69 changes: 39 additions & 30 deletions deeplink_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}()
}
14 changes: 14 additions & 0 deletions test/main.go
Original file line number Diff line number Diff line change
@@ -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 {
}
}

0 comments on commit 75f5c09

Please sign in to comment.