HTTP服务端package mainimport ("fmt""io""net/http")func main() {//resp, _ := http.Get("http://www.baidu.com")//fmt.Println(resp)resp, _ := http.Get("http://127.0.0.1:8000/go")defer resp.Body.Close()// 200 OKfmt.Println(resp.Status)fmt.Println(resp.Header)buf := make([]byte, 1024)for {// 接收服务端信息n, err := resp.Body.Read(buf)if err != nil && err != io.EOF {fmt.Println(err)return} else {fmt.Println("读取完毕")res := string(buf[:n])fmt.Println(res)break}}}
六 WebSocket编程webSocket是什么
- WebSocket是一种在单个TCP连接上进行全双工通信的协议
- WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据
- 在WebSocket API中,浏览器和服务器只需要完成一次握手 , 两者之间就直接可以创建持久性的连接,并进行双向数据传输
- 需要安装第三方包:cmd中:go get -u -v github.com/gorilla/websocket
接收websocket请求的服务端:
package mainimport ( "fmt" "net/http" "github.com/gorilla/websocket")var upgrader = websocket.Upgrader{ ReadBufferSize:1024, WriteBufferSize: 1024,}func main() { http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {conn, _ := upgrader.Upgrade(w, r, nil) // error ignored for sake of simplicityfor {// Read message from browsermsgType, msg, err := conn.ReadMessage()if err != nil {return}// Print the message to the consolefmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))// Write message back to browserif err = conn.WriteMessage(msgType, msg); err != nil {return}} }) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {http.ServeFile(w, r, "H:\\go\\main\\websockets.html") }) http.ListenAndServe(":8080", nil)}
发送websocket请求的客户端:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>WebSockets</title></head><body><input id="input" type="text" /><button onclick="send()">Send</button><pre id="output"></pre><script>var input = document.getElementById("input");var output = document.getElementById("output");var socket = new WebSocket("ws://localhost:8080/echo");socket.onopen = function () {output.innerHTML += "Status: Connected\n";};socket.onmessage = function (e) {output.innerHTML += "Server: " + e.data + "\n";};function send() {socket.send(input.value);input.valuehttps://www.huyubaike.com/biancheng/= "";}</script></body></html>
推荐阅读
- gorm中的关联操作详解
- OnionArch - 采用DDD+CQRS+.Net 7.0实现的洋葱架构
- 摩托罗拉edge s评测_摩托罗拉edge s详细评测
- 一什么千什么的成语 一什么千什么成语
- iQOOz5和iQOOz3的区别_iQOOz5和iQOOz3有哪些差距
- iqoo7的monster模式有什么用_iqoo7的monster的用处是什么
- 对讲机怎么用对讲机使用方法图解(对讲机喊话键下面俩键干什么用的)
- 怎么删除微信上已经添加的朋友(怎么删除微信中已添加的朋友)
- Go中的闭包、递归
- Spring 深入——IoC 容器 01