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
- Cross-platform support (Windows, macOS, Linux)
- Easy to set up and use
- Lightweight and efficient
- Optional statistics dashboard for monitoring connected clients and message relay counts
## Prerequisites
- Go programming language installed (version 1.16 or higher)
@@ -27,6 +29,7 @@ const (
// Update these values before building
EmbeddedServerIP = "0.0.0.0"
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`.
## 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
This project is licensed under the MIT License.

View File

@@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"log"
"time"
"github.com/getlantern/systray"
"github.com/gorilla/websocket"
@@ -15,6 +16,7 @@ var (
lastClipboard []byte
identification string
isConnected bool
serverURL string
)
func onReady() {
@@ -58,7 +60,7 @@ func startClient(statusItem *systray.MenuItem) {
identification = EmbeddedIdentification
server_ip := EmbeddedServerIP
server_port := EmbeddedServerPort
server_connection := "ws://" + server_ip + ":" + server_port + "/ws"
serverURL = "ws://" + server_ip + ":" + server_port + "/ws"
if identification == "" || server_ip == "" || server_port == "" {
log.Println("Missing configuration")
@@ -66,29 +68,70 @@ func startClient(statusItem *systray.MenuItem) {
return
}
// Connect to the server
var connectErr error
conn, _, connectErr = websocket.DefaultDialer.Dial(server_connection, nil)
if connectErr != nil {
log.Println("Error connecting to server:", connectErr)
// Reconnection loop with exponential backoff
backoff := 1 * time.Second
maxBackoff := 60 * time.Second
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")
return
return false
}
// 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
statusItem.SetTitle(fmt.Sprintf("Status: Connected (%s)", identification))
log.Println("Connected to server")
return true
}
// Listen for messages from the server
func listenForMessages(statusItem *systray.MenuItem) {
for {
messageType, message, err := conn.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
isConnected = false
statusItem.SetTitle("Status: Disconnected")
if conn != nil {
conn.Close()
conn = nil
}
return
}
handleMessage(messageType, message)
@@ -109,6 +152,7 @@ func sendMessage(conn *websocket.Conn, messageType int, message []byte) {
err := conn.WriteMessage(messageType, message)
if err != nil {
log.Println("Error sending message:", err)
isConnected = false
}
}

View File

@@ -1,6 +1,7 @@
package main
import (
"fmt"
"log"
"net/http"
"sync"
@@ -8,11 +9,50 @@ import (
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var (
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
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 {
conn *websocket.Conn
@@ -26,6 +66,10 @@ type Server struct {
unregister chan *Client
broadcast chan *Message
mu sync.RWMutex
// Statistics
statsEnabled bool
messagesRelayed uint64
}
type Message struct {
@@ -36,10 +80,11 @@ type Message struct {
func newServer() *Server {
return &Server{
clients: make(map[*Client]bool),
register: make(chan *Client),
unregister: make(chan *Client),
broadcast: make(chan *Message),
clients: make(map[*Client]bool),
register: make(chan *Client),
unregister: make(chan *Client),
broadcast: make(chan *Message),
statsEnabled: EmbeddedServerStats,
}
}
@@ -74,6 +119,11 @@ func (s *Server) run() {
}
}
s.mu.RUnlock()
if s.statsEnabled {
s.mu.Lock()
s.messagesRelayed++
s.mu.Unlock()
}
}
}
}
@@ -157,7 +207,26 @@ func main() {
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)
if EmbeddedServerStats {
log.Printf("Stats dashboard enabled at /stats")
}
err := http.ListenAndServe(":"+port, nil)
if err != nil {
log.Fatal("ListenAndServe error:", err)