76 lines
1.5 KiB
Go
76 lines
1.5 KiB
Go
|
package client
|
||
|
|
||
|
import (
|
||
|
"bufio"
|
||
|
"fmt"
|
||
|
"net"
|
||
|
"os"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
// Connect to the chat server
|
||
|
func connectToServer(address string) (net.Conn, error) {
|
||
|
conn, err := net.Dial("tcp", address)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("could not connect to server: %v", err)
|
||
|
}
|
||
|
return conn, nil
|
||
|
}
|
||
|
|
||
|
// Read input from the terminal and send it to the server
|
||
|
func readInputAndSend(conn net.Conn) {
|
||
|
reader := bufio.NewReader(os.Stdin)
|
||
|
for {
|
||
|
fmt.Print("> ")
|
||
|
text, _ := reader.ReadString('\n')
|
||
|
text = strings.TrimSpace(text)
|
||
|
|
||
|
// Send the command to the server
|
||
|
_, err := conn.Write([]byte(text + "\n"))
|
||
|
if err != nil {
|
||
|
fmt.Println("Error sending message:", err)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
// If the user types 'quit', exit the program
|
||
|
if text == "quit" {
|
||
|
fmt.Println("Goodbye!")
|
||
|
return
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Listen for incoming messages from the server
|
||
|
func listenForMessages(conn net.Conn) {
|
||
|
reader := bufio.NewReader(conn)
|
||
|
for {
|
||
|
message, err := reader.ReadString('\n')
|
||
|
if err != nil {
|
||
|
fmt.Println("Disconnected from server.")
|
||
|
return
|
||
|
}
|
||
|
fmt.Print(message)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
if len(os.Args) < 2 {
|
||
|
fmt.Println("Usage: go run client.go <server-address>")
|
||
|
return
|
||
|
}
|
||
|
|
||
|
serverAddress := os.Args[1]
|
||
|
conn, err := connectToServer(serverAddress)
|
||
|
if err != nil {
|
||
|
fmt.Println(err)
|
||
|
return
|
||
|
}
|
||
|
defer conn.Close()
|
||
|
|
||
|
// Start a goroutine to listen for incoming messages from the server
|
||
|
go listenForMessages(conn)
|
||
|
|
||
|
// Read input from the terminal and send it to the server
|
||
|
readInputAndSend(conn)
|
||
|
}
|