initializ project
This commit is contained in:
65
client.go
Normal file
65
client.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
host = flag.String("host", "localhost", "Server host")
|
||||
port = flag.String("port", "26666", "Server port")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
// Connect to the server
|
||||
conn, err := net.Dial("tcp", *host+":"+*port)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to connect to server: %v\n", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
fmt.Printf("Connected to server %s:%s\n", *host, *port)
|
||||
fmt.Println("Type messages to send to the server (type 'exit' to quit):")
|
||||
|
||||
// Create a scanner to read from standard input
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
|
||||
// Create a goroutine to read messages from the server
|
||||
go func() {
|
||||
serverScanner := bufio.NewScanner(conn)
|
||||
for serverScanner.Scan() {
|
||||
fmt.Printf("Server: %s\n", serverScanner.Text())
|
||||
}
|
||||
}()
|
||||
|
||||
// Read from standard input and send to server
|
||||
for {
|
||||
if !scanner.Scan() {
|
||||
break
|
||||
}
|
||||
|
||||
message := scanner.Text()
|
||||
if strings.TrimSpace(message) == "exit" {
|
||||
fmt.Println("Exiting...")
|
||||
break
|
||||
}
|
||||
|
||||
// Send message to server
|
||||
_, err := fmt.Fprintln(conn, message)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to send message: %v\n", err)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
fmt.Printf("Error reading input: %v\n", err)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user