Golang implementation of H5 chat rooms based on WebSocket protocol

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Http://www.cnblogs.com/wangrudong003/p/5535689.html

Go Code section:

Webchat Project Main.gopackage mainimport ("FMT" "Net/http" "Time" "Encoding/json" "Strings" golang.org/x/net/ WebSocket ")//Global information var datas datasvar users Map[*websocket. Conn]stringfunc Main () {FMT. Println ("Start Time") fmt. Println (time. Now ())//Initialize Datas = Datas{}users = Make (map[*websocket. conn]string)//Bind effect page http. Handlefunc ("/", H_index)//Bind socket method http. Handle ("/websocket", WebSocket. Handler (H_websocket))//Start listening on HTTP. Listenandserve (": 8080", nil)}func H_index (w http. Responsewriter, R *http. Request) {http. Servefile (W, R, "index.html")}func h_websocket (ws *websocket. Conn) {var usermsg usermsgvar data Stringfor {//Determine if the connection is repeated if _, OK: = Users[ws];!ok {USERS[WS] = "Anonymous"}usermsgslen: = Len (da Tas. USERMSGS) fmt. Println ("Usermsgs", Usermsgslen, "Users length:", Len (Users))//When there is a message, the whole part of the data is sent if Usermsgslen > 0 {b, ERRMARSHL: = json. Marshal (datas) if ERRMARSHL! = nil {fmt. PRINTLN ("Global message Content Exception ...") Break}for key, _: = Range users {errmarshl = WebSocket. Message.send (Key, string (b)) if ERRMARSHL! = Nil {//Remove error link Delete (users, KEY) FMT. PRINTLN ("Send error ...") Break}}datas. Usermsgs = Make ([]usermsg, 0)}fmt. Println ("Start parsing data ...") Err: = WebSocket. Message.receive (WS, &data) FMT. PRINTLN ("Data:", "data") if err! = Nil {//Remove the error link from delete (users, WS) FMT. PRINTLN ("Receive error ...") Break}data = strings. Replace (data, "\ n", "", 0) Err = json. Unmarshal ([]byte (data), &usermsg) if err! = Nil {fmt. PRINTLN ("Parse data Exception ...") break}fmt. PRINTLN ("Request data type:", usermsg.datatype) switch Usermsg.datatype {case "send"://Assignment corresponding to the nickname to Wsif _, OK: = Users[ws]; OK {USERS[WS ] = usermsg.username//Clears the connector nickname information Datas. Userdatas = Make ([]userdata, 0)//reload current online connection person for _, Item: = Range users {UserData: = Userdata{username:item}datas. Userdatas = Append (datas. Userdatas, UserData)}}datas. Usermsgs = Append (datas. Usermsgs, usermsg)}}}type usermsg struct {UserName stringmsg stringdatatype string}type UserData struct {UserName str Ing}type Datas struct {usermsgs []usermsguserdatas []userdata}

HTML5 Code section: (Index.html and Main.go placed in the same directory)

<! DOCTYPE html>

  

Download attachments


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.