Skip to content

Instantly share code, notes, and snippets.

@henriquegogo
Created September 29, 2024 04:27
Show Gist options
  • Save henriquegogo/62e1c190bb543073393b1d5306c40cfe to your computer and use it in GitHub Desktop.
Save henriquegogo/62e1c190bb543073393b1d5306c40cfe to your computer and use it in GitHub Desktop.
Sender / Receiver through socket
package main
import (
"fmt"
"net"
"os"
"sync"
"time"
)
const SOCKET_PATH = "/tmp/ipc_socket"
func handleConn(clients *[]net.Conn, mutex *sync.Mutex) {
ipc, _ := net.Listen("unix", SOCKET_PATH)
defer ipc.Close()
fmt.Println("Waiting for connections...")
for {
client, _ := ipc.Accept()
mutex.Lock()
*clients = append(*clients, client)
mutex.Unlock()
fmt.Println("Client connected")
}
}
func sendMessage(clients *[]net.Conn, mutex *sync.Mutex, message string, callback func(string)) {
mutex.Lock()
defer mutex.Unlock()
for i, client := range *clients {
client.Write([]byte(message))
buffer := make([]byte, 1024)
n, err := client.Read(buffer)
if err != nil {
fmt.Println("Client disconnected")
client.Close()
*clients = append((*clients)[:i], (*clients)[i+1:]...)
continue
}
callback(string(buffer[:n]))
}
}
func main() {
if _, err := os.Stat(SOCKET_PATH); err == nil {
os.Remove(SOCKET_PATH)
}
var clients []net.Conn
var mutex sync.Mutex
go handleConn(&clients, &mutex)
for {
message := "Henrique Soares"
sendMessage(&clients, &mutex, message, func(response string) {
fmt.Printf("\"%s\" -> \"%s\"\n", message, response)
})
time.Sleep(1 * time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment