Client tweaks

This commit is contained in:
raul 2024-04-24 16:14:44 +02:00
parent dff54a8d0b
commit b4147d6008
2 changed files with 25 additions and 12 deletions

View File

@ -8,7 +8,7 @@ import (
"fmt" "fmt"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"log" "log"
"os" //"os"
) )
// clientCmd represents the client command // clientCmd represents the client command
@ -21,10 +21,10 @@ with its server.
Example: Example:
./tiny-chat client --ip 192.168.0.100 --port 1337`, ./tiny-chat client --ip 192.168.0.100 --port 1337`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 { // if len(args) == 0 {
cmd.Help() // cmd.Help()
os.Exit(0) // os.Exit(0)
} // }
if err := setClientParameters(cmd); err != nil { if err := setClientParameters(cmd); err != nil {
log.Fatalf("Error happened trying to set parameters: %v\n", err) log.Fatalf("Error happened trying to set parameters: %v\n", err)

View File

@ -6,9 +6,11 @@ import (
"log" "log"
"net" "net"
"os" "os"
"strings"
"time" "time"
"github.com/jroimartin/gocui" "github.com/jroimartin/gocui"
"github.com/nsf/termbox-go"
//"time" //"time"
) )
@ -36,7 +38,11 @@ func Client() {
defer conn.Close() defer conn.Close()
data.Server = conn data.Server = conn
fmt.Print(receiveMessage(conn)) nameRequest, err := receiveMessage(conn)
if err != nil {
log.Fatalf("Error occurred reading from server while requesting name: %v\n", err)
}
fmt.Print(nameRequest)
sendName(conn) sendName(conn)
GUI() GUI()
} }
@ -46,24 +52,31 @@ func Client() {
//////////////////////////////////////////////////// ////////////////////////////////////////////////////
func listenMessages(g *gocui.Gui) { func listenMessages(g *gocui.Gui) {
time.Sleep(time.Second) time.Sleep(time.Millisecond * 250)
chatbox, err := g.View("chatbox") chatbox, err := g.View("chatbox")
if err != nil { if err != nil {
log.Panicln(err) log.Panicln(err)
} }
for { for {
messageFromServer := receiveMessage(data.Server) messageFromServer, err := receiveMessage(data.Server)
fmt.Fprint(chatbox, messageFromServer) if err != nil {
g.Close()
log.Fatalf("Error occurred reading from server: %v\n", err)
}
formattedMessage := strings.TrimRight(messageFromServer, "\n")
fmt.Fprintln(chatbox, formattedMessage)
termbox.Interrupt()
} }
} }
func receiveMessage(conn net.Conn) string { func receiveMessage(conn net.Conn) (s string, err error) {
serverMessage := make([]byte, 2048) serverMessage := make([]byte, 2048)
if _, err := conn.Read(serverMessage); err != nil { if _, err := conn.Read(serverMessage); err != nil {
log.Fatalf("Error occurred reading from server: %v\n", err) return "", err
} }
finalMessage := string(serverMessage) finalMessage := string(serverMessage)
return finalMessage return finalMessage, nil
} }
func sendName(conn net.Conn) { func sendName(conn net.Conn) {