Go语言TCP/UDP Socket编程

1. TCP编程

TCPClient

// TCPClient project main.go
package main import (
"fmt"
"net"
"os"
) func main() {
var buf []byte
if len(os.Args) != {
fmt.Fprintf(os.Stderr, "Usage: %s host:port ", os.Args[])
os.Exit()
}
service := os.Args[]
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
checkErr(err)
conn, err := net.DialTCP("tcp", nil, tcpAddr)
defer conn.Close()
checkErr(err)
rAddr := conn.RemoteAddr()
n, err := conn.Write([]byte("Hello server!"))
checkErr(err)
n, err = conn.Read(buf[:])
checkErr(err)
fmt.Println("Reply from server ", rAddr.String(), string(buf[:n]))
os.Exit()
} func checkErr(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit()
}
}

TCPServer

// TCPServer project main.go
package main import (
"fmt"
"net"
"os"
) func main() {
service := ":5000"
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
checkErr(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkErr(err)
for {
conn, err := listener.Accept()
if err != nil {
continue
}
go handleClient(conn)
}
} func checkErr(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit()
}
} func handleClient(conn net.Conn) {
defer conn.Close()
var buf []byte
for {
n, err := conn.Read(buf[:])
if err != nil {
return
}
rAddr := conn.RemoteAddr()
fmt.Println("Receive from client", rAddr.String(), string(buf[:n]))
_, err2 := conn.Write([]byte("Welcome client!"))
if err2 != nil {
return
}
}
}

2. UDP编程

UPDClient

// UDPClient project main.go
package main import (
"fmt"
"net"
"os"
) func main() {
var buf []byte
if len(os.Args) != {
fmt.Fprintf(os.Stderr, "Usage: %s host:port ", os.Args[])
os.Exit()
}
service := os.Args[]
udpAddr, err := net.ResolveUDPAddr("udp4", service)
checkErr(err)
conn, err := net.DialUDP("udp", nil, udpAddr)
defer conn.Close()
checkErr(err)
rAddr := conn.RemoteAddr()
n, err := conn.Write([]byte("Hello server!"))
checkErr(err)
n, err = conn.Read(buf[:])
checkErr(err)
fmt.Println("Reply from server ", rAddr.String(), string(buf[:n]))
os.Exit()
} func checkErr(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit()
}
}

UDPServer

// UDPServer project main.go
package main import (
"fmt"
"net"
"os"
) func main() {
service := ":5000"
udpAddr, err := net.ResolveUDPAddr("udp4", service)
checkErr(err)
conn, err := net.ListenUDP("udp", udpAddr)
checkErr(err)
for {
handleClient(conn)
}
} func checkErr(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit()
}
} func handleClient(conn *net.UDPConn) {
defer conn.Close()
var buf []byte
for {
n, rAddr, err := conn.ReadFromUDP(buf[:])
if err != nil {
return
}
fmt.Println("Receive from client", rAddr.String(), string(buf[:n]))
_, err2 := conn.WriteToUDP([]byte("Welcome client!"), rAddr)
if err2 != nil {
return
}
}
}
上一篇:tcp/udp socket编程异同


下一篇:字符串连接符