Compare commits

..

2 Commits

Author SHA1 Message Date
Space-Banane
207c5bbf7a Add statistics dashboard 2026-01-17 15:48:05 +01:00
Space-Banane
6b73ca4b21 Implement reconnection logic and improve server connection handling 2026-01-17 15:39:33 +01:00
3 changed files with 143 additions and 18 deletions

View File

@@ -5,6 +5,8 @@ A simple clipboard synchronization tool built with Go. It consists of a server a
- Real-time clipboard synchronization - Real-time clipboard synchronization
- Cross-platform support (Windows, macOS, Linux) - Cross-platform support (Windows, macOS, Linux)
- Easy to set up and use - Easy to set up and use
- Lightweight and efficient
- Optional statistics dashboard for monitoring connected clients and message relay counts
## Prerequisites ## Prerequisites
- Go programming language installed (version 1.16 or higher) - Go programming language installed (version 1.16 or higher)
@@ -27,6 +29,7 @@ const (
// Update these values before building // Update these values before building
EmbeddedServerIP = "0.0.0.0" EmbeddedServerIP = "0.0.0.0"
EmbeddedServerPort = "8080" EmbeddedServerPort = "8080"
EmbeddedServerStats = true
) )
``` ```
@@ -58,6 +61,15 @@ I use this on my home server, which i can connect to with tailscale, so i don't
Clients are identified by the `EmbeddedIdentification` value in the client config file. Make sure to set this to a unique value for each USER you want to sync. If you want to sync multiple devices for the same user, just run multiple instances of the client with the same `EmbeddedIdentification`. Clients are identified by the `EmbeddedIdentification` value in the client config file. Make sure to set this to a unique value for each USER you want to sync. If you want to sync multiple devices for the same user, just run multiple instances of the client with the same `EmbeddedIdentification`.
## Statistics Dashboard
If `EmbeddedServerStats` is set, the server will serve a live statistics dashboard at [http://localhost:8080/stats](http://localhost:8080/stats) showing:
- Number of connected clients
- Number of messages relayed
The dashboard uses [Tailwind CSS CDN](https://cdn.tailwindcss.com) for styling and updates live every second.
## License ## License
This project is licensed under the MIT License. This project is licensed under the MIT License.

View File

@@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"log" "log"
"time"
"github.com/getlantern/systray" "github.com/getlantern/systray"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
@@ -15,6 +16,7 @@ var (
lastClipboard []byte lastClipboard []byte
identification string identification string
isConnected bool isConnected bool
serverURL string
) )
func onReady() { func onReady() {
@@ -58,7 +60,7 @@ func startClient(statusItem *systray.MenuItem) {
identification = EmbeddedIdentification identification = EmbeddedIdentification
server_ip := EmbeddedServerIP server_ip := EmbeddedServerIP
server_port := EmbeddedServerPort server_port := EmbeddedServerPort
server_connection := "ws://" + server_ip + ":" + server_port + "/ws" serverURL = "ws://" + server_ip + ":" + server_port + "/ws"
if identification == "" || server_ip == "" || server_port == "" { if identification == "" || server_ip == "" || server_port == "" {
log.Println("Missing configuration") log.Println("Missing configuration")
@@ -66,29 +68,70 @@ func startClient(statusItem *systray.MenuItem) {
return return
} }
// Connect to the server // Reconnection loop with exponential backoff
var connectErr error backoff := 1 * time.Second
conn, _, connectErr = websocket.DefaultDialer.Dial(server_connection, nil) maxBackoff := 60 * time.Second
if connectErr != nil {
log.Println("Error connecting to server:", connectErr) for {
if connectToServer(statusItem) {
// Successfully connected, reset backoff
backoff = 1 * time.Second
// Listen for messages until connection drops
listenForMessages(statusItem)
}
// Connection failed or dropped, wait before retry
isConnected = false
statusItem.SetTitle(fmt.Sprintf("Status: Reconnecting in %ds...", int(backoff.Seconds())))
log.Printf("Reconnecting in %s...", backoff)
time.Sleep(backoff)
// Increase backoff exponentially
backoff *= 2
if backoff > maxBackoff {
backoff = maxBackoff
}
}
}
func connectToServer(statusItem *systray.MenuItem) bool {
statusItem.SetTitle("Status: Connecting...")
var err error
conn, _, err = websocket.DefaultDialer.Dial(serverURL, nil)
if err != nil {
log.Println("Error connecting to server:", err)
statusItem.SetTitle("Status: Connection failed") statusItem.SetTitle("Status: Connection failed")
return return false
} }
// Send identification to the server // Send identification to the server
sendMessage(conn, websocket.TextMessage, []byte(identification)) err = conn.WriteMessage(websocket.TextMessage, []byte(identification))
if err != nil {
log.Println("Error sending identification:", err)
conn.Close()
conn = nil
return false
}
isConnected = true isConnected = true
statusItem.SetTitle(fmt.Sprintf("Status: Connected (%s)", identification)) statusItem.SetTitle(fmt.Sprintf("Status: Connected (%s)", identification))
log.Println("Connected to server") log.Println("Connected to server")
return true
}
// Listen for messages from the server func listenForMessages(statusItem *systray.MenuItem) {
for { for {
messageType, message, err := conn.ReadMessage() messageType, message, err := conn.ReadMessage()
if err != nil { if err != nil {
log.Println("Error reading message:", err) log.Println("Error reading message:", err)
isConnected = false isConnected = false
statusItem.SetTitle("Status: Disconnected") statusItem.SetTitle("Status: Disconnected")
if conn != nil {
conn.Close()
conn = nil
}
return return
} }
handleMessage(messageType, message) handleMessage(messageType, message)
@@ -109,6 +152,7 @@ func sendMessage(conn *websocket.Conn, messageType int, message []byte) {
err := conn.WriteMessage(messageType, message) err := conn.WriteMessage(messageType, message)
if err != nil { if err != nil {
log.Println("Error sending message:", err) log.Println("Error sending message:", err)
isConnected = false
} }
} }

View File

@@ -1,6 +1,7 @@
package main package main
import ( import (
"fmt"
"log" "log"
"net/http" "net/http"
"sync" "sync"
@@ -8,12 +9,51 @@ import (
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
var upgrader = websocket.Upgrader{ var (
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { CheckOrigin: func(r *http.Request) bool {
return true return true
}, },
} }
dashboardHTML = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Clipboard On The Go - Stats</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen flex flex-col items-center justify-center">
<div class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4 w-full max-w-md">
<h1 class="text-2xl font-bold mb-4 text-center">Clipboard On The Go - Server Stats</h1>
<div class="mb-2 flex justify-between">
<span class="font-semibold">Connected Clients:</span>
<span id="clients" class="font-mono">0</span>
</div>
<div class="mb-2 flex justify-between">
<span class="font-semibold">Messages Relayed:</span>
<span id="messages" class="font-mono">0</span>
</div>
</div>
<script>
function updateStats() {
fetch('/stats/data')
.then(r => r.json())
.then(d => {
document.getElementById('clients').textContent = d.clients;
document.getElementById('messages').textContent = d.messages;
});
}
setInterval(updateStats, 1000);
updateStats();
</script>
</body>
</html>
`
)
type Client struct { type Client struct {
conn *websocket.Conn conn *websocket.Conn
identification string identification string
@@ -26,6 +66,10 @@ type Server struct {
unregister chan *Client unregister chan *Client
broadcast chan *Message broadcast chan *Message
mu sync.RWMutex mu sync.RWMutex
// Statistics
statsEnabled bool
messagesRelayed uint64
} }
type Message struct { type Message struct {
@@ -40,6 +84,7 @@ func newServer() *Server {
register: make(chan *Client), register: make(chan *Client),
unregister: make(chan *Client), unregister: make(chan *Client),
broadcast: make(chan *Message), broadcast: make(chan *Message),
statsEnabled: EmbeddedServerStats,
} }
} }
@@ -74,6 +119,11 @@ func (s *Server) run() {
} }
} }
s.mu.RUnlock() s.mu.RUnlock()
if s.statsEnabled {
s.mu.Lock()
s.messagesRelayed++
s.mu.Unlock()
}
} }
} }
} }
@@ -157,7 +207,26 @@ func main() {
handleWebSocket(server, w, r) handleWebSocket(server, w, r)
}) })
// Serve stats dashboard if enabled
if EmbeddedServerStats {
http.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, dashboardHTML)
})
http.HandleFunc("/stats/data", func(w http.ResponseWriter, r *http.Request) {
server.mu.RLock()
clients := len(server.clients)
messages := server.messagesRelayed
server.mu.RUnlock()
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"clients":%d,"messages":%d}`, clients, messages)
})
}
log.Printf("Server starting on port %s", port) log.Printf("Server starting on port %s", port)
if EmbeddedServerStats {
log.Printf("Stats dashboard enabled at /stats")
}
err := http.ListenAndServe(":"+port, nil) err := http.ListenAndServe(":"+port, nil)
if err != nil { if err != nil {
log.Fatal("ListenAndServe error:", err) log.Fatal("ListenAndServe error:", err)