html5运用go+websocket搭建websocket办事的实例-
发布时间:08/01 来源:未知 浏览:
关键词:
这次的就直接发放代码截图吧,应当是用go说话做后台一个简易的谈天,这里没用到什么特殊的见识,最精打细算的来实现结果,主要目的是分享下h5如何用websocket,go搭建websocket办事的主要局部。
go代码局部:
// WebChat project main.go package main import ( "fmt" "net/http" "time" "encoding/json" "strings" "golang.org/x/net/websocket" ) //全局信息 var datas Datas var users map[*websocket.Conn]string func main() { fmt.Println("启动工夫") fmt.Println(time.Now()) //初始化 datas = Datas{} users = make(map[*websocket.Conn]string) //绑定结果页面 http.HandleFunc("/", h_index) //绑定socket办法 http.Handle("/webSocket", websocket.Handler(h_webSocket)) //开端监听 http.ListenAndServe(":8", nil) } func h_index(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "index.html") } func h_webSocket(ws *websocket.Conn) { var userMsg UserMsg var data string for { //推断可否反复连贯 if _, ok := users[ws]; !ok { users[ws] = "匿名" } userMsgsLen := len(datas.UserMsgs) fmt.Println("UserMsgs", userMsgsLen, "users长度:", len(users)) //有新闻时,全局部发送数据 if userMsgsLen > 0 { b, errMarshl := json.Marshal(datas) if errMarshl != nil { fmt.Println("全局新闻内容异样...") break } for key, _ := range users { errMarshl = websocket.Message.Send(key, string(b)) if errMarshl != nil { //移除出错的链接 delete(users, key) fmt.Println("发送出错...") break } } datas.UserMsgs = make([]UserMsg, 0) } fmt.Println("开端解析数据...") err := websocket.Message.Receive(ws, &data) fmt.Println("data:", data) if err != nil { //移除出错的链接 delete(users, ws) fmt.Println("接收出错...") break } data = strings.Replace(data, "\n", "", 0) err = json.Unmarshal([]byte(data), &userMsg) if err != nil { fmt.Println("解析数据异样...") break } fmt.Println("要求数据类型:", userMsg.DataType) switch userMsg.DataType { case "send": //赋值对应的昵称到ws if _, ok := users[ws]; ok { users[ws] = userMsg.UserName //革除连贯人昵称信息 datas.UserDatas = make([]UserData, 0) //从新加载目前在线连贯人 for _, item := range users { userData := UserData{UserName: item} datas.UserDatas = append(datas.UserDatas, userData) } } datas.UserMsgs = append(datas.UserMsgs, userMsg) } } } type UserMsg struct { UserName string Msg string DataType string } type UserData struct { UserName string } type Datas struct { UserMsgs []UserMsg UserDatas []UserData }
html代码局部:
打赏