Examples of Golang WebSocket

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

Recently wrote a chrome websocket extension, server End with Java Netty Framework, later found Golang implementation websocket very simple, efficient, the following is an example, simple implementation of user login, broadcast, equivalent to chat room!


Package Mainimport ("Code.google.com/p/go.net/websocket" "Html/template" "Log" "Net/http" "OS" "Strings" "Time") const ( LISTENADDR = "localhost:9527"//server address) Var (pwd, _ = os. GETWD () roottemp = template. Must (template. Parsefiles (pwd + "/chat.html")) JSON = WebSocket. JSON//codec for jsonmessage = WebSocket.          Message//codec for string, []byteactiveclients = Make (map[clientconn]string)//Map containing Clientsuser  = Make (map[string]string))//Initialize handlers and WebSocket handlersfunc init () {user["AAA"] = "AAA" user["bbb"] = "BBB" user["test"] = "test" user["test2"] = "test2" user["test3"] = "test3"}//Client connection consists of the WebSocket a nd the client iptype clientconn struct {websocket *websocket. Connclientip string}//WebSocket Server to handle chat between Clientsfunc sockserver (WS *websocket. Conn) {var err errorvar clientmessage string//use []byte if WebSocket binary type is blob or arraybuffer//var clientmess AGE []byte//cleanup on Server sidedefer func () {if Err = ws. Close (); Err! = Nil {log. Println ("Websocket could not be closed", err. Error ())}} () client: = ws. Request (). REMOTEADDRLOG.PRINTLN ("Client connected:", client) Sockcli: = Clientconn{ws, client}activeclients[sockcli] = "" Log.  Println ("Number of clients connected:", Len (activeclients))//For loops so the websocket stays open otherwise//it ' ll close After one receieve and sendfor {if Err = message.receive (WS, &clientmessage); Err! = Nil {//If we cannot Read then T He connection is closedlog. Println ("Websocket disconnected Waiting", err. Error ())//Remove the WS client conn from our active clientsdelete (activeclients, sockcli) log. Println ("Number of clients still connected:", Len (activeclients)) Return}var Msg_arr = strings. Split (clientmessage, "|") If msg_arr[0] = = "Login" && len (msg_arr) = = 3 {Name: = Msg_arr[1]pass: = msg_arr[2]if pass = = User[name] {activecl IENTS[SOCKCLI] = Nameif err = message.send (WS, "login|" +name); Err! = Nil {log. Println ("Could not send Message to", client, err.) Error ())}} else {log. PRINTLN ("Login faild:", Clientmessage)}} else if msg_arr[0] = = "MSG" {if ACTIVECLIENTS[SOCKCLI]! = "" {clientmessage = "ms G| "+ time. Now ().  Format ("2006-01-02 15:04:05") + "" + ACTIVECLIENTS[SOCKCLI] + "said:" + msg_arr[1]for cs, na: = Range activeclients {if Na! = "" {If Err = Message.send (Cs.websocket, clientmessage); Err! = Nil {log. Println ("Could not send Message to", Cs.clientip, err.) Error ())}}}}}}}//Roothandler renders the template for the root pagefunc roothandler (w http. Responsewriter, req *http. Request) {err: = Roottemp.execute (W, listenaddr) if err! = Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror)}}func Main () {http. Handlefunc ("/", Roothandler) http. Handle ("/socket", WebSocket. Handler (Sockserver)) Err: = http. Listenandserve (listenaddr, nil) if err! = Nil {Panic ("Listenandserve:" + Err. Error ())}}


Related Article

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.