TCP 服务器 (tcp_server.go):
goCopy code
package main
import (
"fmt"
"net"
)
const (
serverAddr = "127.0.0.1:12345"
)
func main() {
// 创建监听器
listener, err := net.Listen("tcp", serverAddr)
if err != nil {
fmt.Println("Error listening:", err)
return
}
defer listener.Close()
fmt.Println("TCP server listening on", serverAddr)
// 等待客户端连接
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
return
}
// 处理客户端连接
go handleClient(conn)
}
}
func handleClient(conn net.Conn) {
defer conn.Close()
// 读取客户端发送的数据
buffer := make([]byte, 1024)
n, err := conn.Read(buffer)
if err != nil {
fmt.Println("Error reading from client:", err)
return
}
fmt.Printf("Received message from client: %s\n", string(buffer[:n]))
// 向客户端发送响应数据
message := []byte("Hello, TCP Client!")
_, err = conn.Write(message)
if err != nil {
fmt.Println("Error writing to client:", err)
return
}
}
TCP 客户端 (tcp_client.go):
goCopy code
package main
import (
"fmt"
"net"
)
const (
serverAddr = "127.0.0.1:12345"
)
func main() {
// 连接服务器
conn, err := net.Dial("tcp", serverAddr)
if err != nil {
fmt.Println("Error connecting to server:", err)
return
}
defer conn.Close()
// 向服务器发送数据
message := []byte("Hello, TCP Server!")
_, err = conn.Write(message)
if err != nil {
fmt.Println("Error writing to server:", err)
return
}
// 读取服务器的响应
buffer := make([]byte, 1024)
n, err := conn.Read(buffer)
if err != nil {
fmt.Println("Error reading from server:", err)
return
}
fmt.Printf("Received response from server: %s\n", string(buffer[:n]))
}