Websocket简单运用
- 是什么:全双工通信协议。
- 能做什么:服务端可以主动的发送数据给客户端
- golang应用到的包
go get github.com/gorilla/websocket
server.go
package main
import(
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
// 设置合适读取字节
var upgrader = websocket.Upgrader{
ReadBufferSize:1024,
WriteBufferSize:1024,
CheckOrigin:func(r *http.Request)bool{
return true
}, // 解决跨域
}
func init(){
log.SetFlags(log.Ltime|log.Lshortfile)
}
func ServerHTTP(w http.ResponseWriter,r *http.Request){
log.Printf("客户端地址:%v",r.RemoteAddr)
conn,err := upgrader.Upgrade(w,r,nil)
if err!=nil{
log.Printf("将连接升级为websocket失败:%v\n",err)
return
}
// 循环不断地接收信息,和发送信息
for{
// 读取信息
messageType,p,err := conn.ReadMessage()
if err!=nil{
log.Printf("读取客户端发送信息失败:%v\n",err)
return
}
log.Printf("客户端发送地数据类型:%d,发送地数据:%v",messageType,string(p))
// 客户端发送数据给服务端
if err:=conn.WriteMessage(messageType,p);err!=nil{
log.Printf("发送数据失败:%v",err)
return
}
}
}
func main(){
fmt.Println("websocket的简单应用")
http.HandleFunc("/ws",ServerHTTP)
if err:=http.ListenAndServe(":8080",nil);err!=nil{
log.Printf("打开服务有误:%v",err)
}
}
client(angular)
WebsocketTest(){
if("WebSocket" in window){
console.log("支持websocket")
}else{
console.warn("不支持websocket")
return
}
var ws = new WebSocket("ws://localhost:8080/ws")
ws.onopen = ()=>{
ws.send("发送数据")
}
ws.onmessage = (e:any)=>{
console.log("接收数据为",e.data)
}
ws.onclose = ()=>{
console.log("连接关闭")
}
}