在本教程中,我们将通过构建一个简单而强大的 TCP/IP 服务器和客户端来揭开网络编程的神秘面纱。如果您曾经想知道应用程序如何通过网络进行通信,本指南适合您!
在深入研究代码之前,让我们先来分析一下两台计算机通话时发生的情况:
TCP/IP:把它想象成一个电话
服务器和客户端角色:
tcp-chat-app/ ├── server/ │ └── server.go # Server-side logic ├── client/ │ └── client.go # Client-side logic └── main.go # Starts both server and client
package server import ( "log" "net" ) // StartServer: Our digital receptionist func StartServer() { // Choose a "phone number" (address) address := "localhost:8080" // Set up a "phone line" to listen for calls listener, err := net.Listen("tcp", address) if err != nil { log.Fatalf("Couldn't set up the phone line: %v", err) } defer listener.Close() log.Printf("Server is ready, waiting for connections on %s", address) // Forever wait for incoming "calls" for { // Accept a new connection conn, err := listener.Accept() if err != nil { log.Printf("Missed a call: %v", err) continue } // Handle each "caller" in a separate conversation go handleClient(conn) } }
func handleClient(conn net.Conn) { // Always clean up after the conversation defer conn.Close() log.Printf("New client connected: %s", conn.RemoteAddr()) // Prepare a message buffer buffer := make([]byte, 1024) // Keep the conversation going for { // Read message from client n, err := conn.Read(buffer) if err != nil { log.Printf("Connection error: %v", err) return } // Echo the message back message := string(buffer[:n]) log.Printf("Received: %s", message) conn.Write([]byte("Server says: " + message)) } }
package client import ( "bufio" "fmt" "log" "net" "os" ) func StartClient() { // Dial the server (like making a phone call) conn, err := net.Dial("tcp", "localhost:8080") if err != nil { log.Printf("Could not connect to server: %v", err) return } defer conn.Close() fmt.Println("Connected to server. Start chatting!") // Read user input and send to server scanner := bufio.NewScanner(os.Stdin) for { fmt.Print("> ") if !scanner.Scan() { break } message := scanner.Text() if message == "exit" { break } // Send message to server conn.Write([]byte(message + "\n")) // Wait for server's response response := make([]byte, 1024) n, err := conn.Read(response) if err != nil { log.Printf("Error receiving response: %v", err) break } fmt.Println(string(response[:n])) } }
package main import ( "time" "tcpIp/server" "tcpIp/client" ) func main() { // Start server in background go func() { server.StartServer() }() // Give server a moment to start time.Sleep(time.Second) // Launch client client.StartClient() }
go run main.go
管理。(2023 年 8 月 9 日)。通过适用于所有人的免费交换和路由指南来学习 TCP/IP。诅咒。 https://cursin.net/en/learn-tcp-ip-with-the-free-switching-and-routing-guide-for-everyone/
伍德贝克,A.(2021)。使用 Go 进行网络编程。无淀粉压榨公司
祝您网络愉快! ??
以上是网络:Go 中的第一个 TCP/IP 服务器和客户端的详细内容。更多信息请关注PHP中文网其他相关文章!