diff --git a/chat_client.go b/chat_client.go index 8784cf5..a22c5d8 100644 --- a/chat_client.go +++ b/chat_client.go @@ -293,6 +293,31 @@ func showErrorDialog(parent *gtk.Window, message string) { dialog.Destroy() // Clean up the dialog } +func tryReconnect(conn *net.Conn, window *gtk.Window, addr string, config *Config) error { + var newConn net.Conn + var err error + + if config.Connection.Protocol == "tcp" { + newConn, err = net.Dial("tcp", addr) + } else { + udpAddr, resolveErr := net.ResolveUDPAddr("udp", addr) + if resolveErr != nil { + return fmt.Errorf("failed to resolve UDP address: %v", resolveErr) + } + newConn, err = net.DialUDP("udp", nil, udpAddr) + } + + if err != nil { + showErrorDialog(window, "Failed to reconnect. Exiting...") + gtk.MainQuit() + return err + } + + // Update the caller's connection variable + *conn = newConn + return nil +} + func main() { // Load configuration config, err := loadConfig("chat_client.yaml") @@ -356,12 +381,6 @@ func main() { entryObj, _ := builder.GetObject("entry") entry := entryObj.(*gtk.Entry) - - // Connect the "destroy" signal to quit the application - window.Connect("destroy", func() { - fmt.Println("Window closed") - gtk.MainQuit() - }) // Setup connection addr := fmt.Sprintf("%s:%d", config.Connection.IP, config.Connection.Port) @@ -375,6 +394,13 @@ func main() { conn, connErr = net.DialUDP("udp", nil, udpAddr) } + // Connect the "destroy" signal to quit the application + window.Connect("destroy", func() { + fmt.Println("Window closed") + say(conn, "Good Bye, User(Off-Line)", config.User.Username, timezone) + gtk.MainQuit() + }) + if connErr != nil { fmt.Printf("Connection error (%s://%s): %v\n", config.Connection.Protocol, addr, connErr) showErrorDialog(window, "Unable to connect to the server. Please check the server and try again.") @@ -396,9 +422,15 @@ func main() { buf := make([]byte, 1024) n, err := conn.Read(buf) if err != nil { - break + //if err == io.EOF { + showErrorDialog(window, "Disconnected, try again...") + err := tryReconnect(&conn, window, addr, config) + if err != nil { + fmt.Printf("Reconnection failed: %v\n", err) + gtk.MainQuit() + } + continue } - decrypted, err := encryptor.Decrypt(buf[:n]) if err != nil { continue @@ -426,5 +458,4 @@ func main() { window.ShowAll() gtk.Main() - say(conn, "Good Bye, User(Off-Line)", config.User.Username, timezone) }