服务端server.go
package main
import (
"fmt"
"net"
)
/*
服务端处理流程
a.监听端口
b.接收客户端链接
c.创建goroutine,处理该链接
*/
func main() {
listen, err := net.Listen("tcp", "0.0.0.0:20000")
if err != nil {
fmt.Println("listen failed,err:", err)
return
}
for {
conn, err := listen.Accept()
if err != nil {
fmt.Println("accept failed,err:%v\n", err)
continue
}
go process(conn)
}
}
func process(conn net.Conn) {
defer conn.Close()
for {
var buf [128]byte
n, err := conn.Read(buf[:])
if err != nil {
panic(err)
}
str := string(buf[:n])
fmt.Printf("recv from client, data: %v\n", str)
}
}
客户端client.go
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
/*
客户端编程模式
a.建立与服务端的链接
b.进行数据收发
c.关闭链接
*/
func main() {
conn,err := net.Dial("tcp","0.0.0.0:20000")
if err != nil {
fmt.Println("dail failed, err :",err)
return
}
reader := bufio.NewReader(os.Stdin)
for {
data, err := reader.ReadString('\n')
if err != nil {
fmt.Printf("read from console,err: %v\n",err)
break
}
data = strings.TrimSpace(data)
_ ,err = conn.Write([]byte(data))
if err != nil {
fmt.Printf("write failed ,err:%v\n",err)
break
}
}
}
============================================================================
http服务器
package main
import "net/http"
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world!"))
})
http.ListenAndServe(":9090",nil)
}
================================================================================================
package main
import (
"fmt"
"net/http"
)
func sayhello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world!"))
fmt.Fprintf(w,"%v\n",r.Form)
fmt.Fprintf(w,"path:%s\n",r.URL.Path)
fmt.Fprintf(w,"schema\n",r.URL.Scheme)
fmt.Fprintf(w,"hello world!\n")
}
func main() {
http.HandleFunc("/", sayhello)
http.ListenAndServe(":9090",nil)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)