8.1
下面展示一些 代码
。
package mainimport ("fmt""net""os""time"
)type Clock struct {Name stringAddr string
}
func main() {clocks := []Clock{{Name: "New York", Addr: "localhost:8000"},{Name: "London", Addr: "localhost:8001"},{Name: "Tokyo", Addr: "localhost:8002"},}fmt.Printf("%-15s %s\n", "Location", "Time")for _, clock := range clocks {conn, err := net.Dial("tcp", clock.Addr)if err != nil {fmt.Fprintf(os.Stderr, "Error connecting to %s: %v\n", clock.Name, err)continue}defer conn.Close()// 读取服务器发送的时间var timeStr string_, err = fmt.Fscan(conn, &timeStr)if err != nil {fmt.Fprintf(os.Stderr, "Error reading time from %s: %v\n", clock.Name, err)continue}// 解析时间t, err := time.Parse(time.RFC3339, timeStr)if err != nil {fmt.Fprintf(os.Stderr, "Error parsing time from %s: %v\n", clock.Name, err)continue}fmt.Printf("%-15s %s\n", clock.Name, t.Format(time.RFC3339))}
}
8.2
下面展示一些 代码
。
package mainimport ("bufio""fmt""net""os""strings"
)func handleClient(conn net.Conn) {defer conn.Close()reader := bufio.NewReader(conn)writer := bufio.NewWriter(conn)for {// 读取客户端发送的命令cmd, err := reader.ReadString('\n')if err != nil {fmt.Println("Error reading command:", err)return}// 去除命令中的空白字符cmd = strings.TrimSpace(cmd)// 解析并处理命令switch cmd {case "cd":// 处理 cd 命令_, err := writer.WriteString("Change directory command executed.\n")if err != nil {fmt.Println("Error writing response:", err)return}writer.Flush()case "quit":// 处理退出命令returndefault:_, err := writer.WriteString("Unknown command.\n")if err != nil {fmt.Println("Error writing response:", err)return}writer.Flush()}}
}func main() {listener, err := net.Listen("tcp", ":2121")if err != nil {fmt.Println("Error starting server:", err)return}defer listener.Close()fmt.Println("Server started, waiting for connections...")for {conn, err := listener.Accept()if err != nil {fmt.Println("Error accepting connection:", err)continue}go handleClient(conn)}
}