TCP协议
TCP服务端编程:
package main
import (
"fmt"
"net"
"os"
)
func clientor(c net.Conn) {
clientAddr := c.RemoteAddr().String()
for {
buf := make([]byte, 128)
_, err := c.Read(buf)
if err != nil {
fmt.Println("conneter read error.", err)
break
}
fmt.Printf("[%v]:%v\n", clientAddr, string(buf))
c.Write([]byte("收到!"))
}
}
func main() {
listener, err := net.Listen("tcp", "127.0.0.1:8888")
if err != nil {
fmt.Println("tcp listen error.", err)
os.Exit(1)
}
for {
conneter, err := listener.Accept()
if err != nil {
fmt.Println("listener accept error.", err)
os.Exit(2)
}
go clientor(conneter)
}
}
TCP客户端编程:
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
"sync"
)
var wg sync.WaitGroup
func server(c net.Conn) {
defer wg.Done()
serverAddr := c.RemoteAddr().String()
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("# ")
msg, _ := reader.ReadString('\n')
msg = strings.TrimSpace(msg)
c.Write([]byte(msg))
buf := make([]byte, 128)
_, err := c.Read(buf)
if err != nil {
fmt.Println("conneter read error.", err)
}
fmt.Printf("[%v]:%v\n", serverAddr, string(buf))
}
}
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:8888")
if err != nil {
fmt.Println("tcp Dial error.", err)
os.Exit(1)
}
wg.Add(1)
go server(conn)
wg.Wait()
}
UDP协议
UDP服务端编程:
package main
import (
"fmt"
"net"
"os"
"strings"
)
func checkErr(err error) {
if err != nil {
fmt.Println("ERROR:", err)
os.Exit(1)
}
}
func main() {
udpSocket, err := net.ListenUDP("udp", &net.UDPAddr{
IP: net.IPv4(127, 0, 0, 1),
Port: 8888,
})
checkErr(err)
defer udpSocket.Close()
fmt.Println("UDP服务已启动...")
for {
readbuf := make([]byte, 128)
_, rAddr, err := udpSocket.ReadFromUDP(readbuf)
checkErr(err)
fmt.Printf("[%v]:%s\n", rAddr.String(), readbuf)
writebuf := []byte(strings.ToUpper(string(readbuf)))
_, err = udpSocket.WriteToUDP(writebuf, rAddr)
checkErr(err)
}
}
UDP客户端编程:
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func checkErr(err error) {
if err != nil {
fmt.Println("ERROR:", err)
os.Exit(1)
}
}
func main() {
socket, err := net.DialUDP("udp", nil, &net.UDPAddr{
IP: net.IPv4(127, 0, 0, 1),
Port: 8888,
})
checkErr(err)
defer socket.Close()
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("请输入:")
msg, _ := reader.ReadString('\n')
msg = strings.TrimSpace(msg)
_, err = socket.Write([]byte(msg))
checkErr(err)
buf := make([]byte, 128)
_, rAddr, err := socket.ReadFromUDP(buf)
checkErr(err)
fmt.Printf("[%v]:%s\n", rAddr.String(), buf)
}
}
HTTP协议
HTTP服务端编程:
package main
import (
"io/ioutil"
"net/http"
)
func TestShow(response http.ResponseWriter, request *http.Request) {
ret, err := ioutil.ReadFile("./xx.txt")
if err != nil {
response.Write([]byte(err.Error()))
}
response.Write([]byte(ret))
}
func main() {
http.HandleFunc("/TestShow", TestShow)
http.ListenAndServe("127.0.0.1:8080", nil)
}
HTTP客户端编程:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func checkErr(err error) {
if err != nil {
fmt.Println("ERROR:", err)
os.Exit(1)
}
}
func main() {
resp, err := http.Get("https://www.baidu.com")
checkErr(err)
buf, err := ioutil.ReadAll(resp.Body)
checkErr(err)
fmt.Println(string(buf))
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
)
func checkErr(err error) {
if err != nil {
fmt.Println("ERROR:", err)
os.Exit(1)
}
}
func main() {
data := url.Values{}
data.Set("name", "张三")
data.Set("age", "100")
queryStr := data.Encode()
fmt.Println(queryStr)
urlObj, _ := url.Parse("https://www.baidu.com")
urlObj.RawQuery = queryStr
req, err := http.NewRequest("GET", urlObj.String(), nil)
checkErr(err)
fmt.Println(req.URL.String())
resp, err := http.DefaultClient.Do(req)
checkErr(err)
buf, err := ioutil.ReadAll(resp.Body)
checkErr(err)
fmt.Println(string(buf))
defer resp.Body.Close()
}
|