Go语言实战:Go的网络编程与TCP_UDP
以下是针对Go语言网络编程的TCP和UDP的简单示例代码。
TCP服务器端:
package main
import (
"fmt"
"net"
)
func main() {
listener, err := net.Listen("tcp", "localhost:50000")
if err != nil {
fmt.Println(err)
return
}
defer listener.Close()
fmt.Println("Listening on localhost:50000...")
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println(err)
continue
}
go handleTCPConnection(conn)
}
}
func handleTCPConnection(conn net.Conn) {
defer conn.Close()
fmt.Fprintf(conn, "Hello, client! Type 'exit' to quit.\n")
for {
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
return
}
if string(buf[:n-1]) == "exit" {
fmt.Println("Client exited.")
return
}
fmt.Fprintf(conn, "Received: %s\n", string(buf[:n-1]))
}
}
TCP客户端:
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func main() {
conn, err := net.Dial("tcp", "localhost:50000")
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
go func() {
reader := bufio.NewReader(os.Stdin)
for {
data, err := reader.ReadString('\n')
if err != nil {
fmt.Println(err)
return
}
trimmedData := strings.TrimSpace(data)
if trimmedData == "exit" {
conn.Close()
return
}
conn.Write([]byte(trimmedData))
}
}()
for {
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Server: %s\n", string(buf[:n]))
}
}
UDP服务器端:
package main
import (
"fmt"
"net"
)
func main() {
addr, err := net.ResolveUDPAddr("udp", "localhost:50001")
if err != nil {
fmt.Println(err)
return
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
fmt.Println("Listening on localhost:50001...")
for {
handleUDPConnection(conn)
}
}
func handleUDPConnection(conn *net.UDPConn) {
buffer := make([]byte, 1024)
n, addr, err := conn.ReadFromUDP(buffer)
if err != nil {
fmt.Println(err)
return
}
message := string(buffer[:n])
fmt.Printf("Received message: %s from %s\n", message, addr)
_, err = conn.WriteToUDP([]byte("Hello, client!"),
评论已关闭