mini-chat/cmd/client.go

95 lines
1.9 KiB
Go
Raw Normal View History

2024-04-02 11:27:48 +02:00
/*
Copyright © 2024 Raul
*/
package cmd
import (
"bufio"
2024-04-02 11:27:48 +02:00
"fmt"
"github.com/jroimartin/gocui"
"github.com/spf13/cobra"
"log"
2024-04-02 11:27:48 +02:00
"net"
"os"
)
// clientCmd represents the client command
var clientCmd = &cobra.Command{
Use: "client",
Short: "Connect to a mini-chat server",
Long: `Connect to a mini-chat server.
Example:
./mini-chat client --ip 192.168.0.50 --port 1337`,
2024-04-02 11:27:48 +02:00
Run: func(cmd *cobra.Command, args []string) {
client(cmd)
},
}
var err error
var conn net.Conn
2024-04-02 11:27:48 +02:00
func init() {
rootCmd.AddCommand(clientCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// clientCmd.PersistentFlags().String("foo", "", "A help for foo")
clientCmd.Flags().String("ip", "", "Server to connect to")
clientCmd.Flags().String("port", "1302", "Port to connect to")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// clientCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
func client(cmd *cobra.Command) {
port, _ := cmd.Flags().GetString("port")
ip, _ := cmd.Flags().GetString("ip")
if ip == "" {
fmt.Println("Not enough arguments, run \"-h\" parameter to see all the parameters!")
os.Exit(0)
}
if port == "" {
port = "1302"
2024-04-02 11:27:48 +02:00
}
socket := ip + ":" + port
conn, err = net.Dial("tcp", socket)
cobra.CheckErr(err)
defer conn.Close()
reply := make([]byte, 1024)
conn.Read(reply)
fmt.Print(string(reply))
msg, err := bufio.NewReader(os.Stdin).ReadString('\n')
cobra.CheckErr(err)
conn.Write([]byte(msg))
ui(conn)
}
func sendmsg(g *gocui.Gui, v *gocui.View) error {
textarea, err := g.View("textarea")
if err != nil {
log.Panicln(err)
}
message := textarea.Buffer()
msg := string(message)
if msg == "" {
return nil
}
if msg == "" {
return nil
}
fmt.Fprint(conn, msg)
textarea.Clear()
textarea.SetCursor(0, 0)
return nil
2024-04-02 11:27:48 +02:00
}