WebSocket server base on Go language

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

Before using the commercial server provided by pusher.com, but in my station slow, message delivery is lost, so self-framing

The main implementation of the notification function:

1. According to each page's session_id to distinguish the connection, the array way to store, should when a session opens the multiple page the case

2.json format for communication, the data specified to notify the session, all page under the session will be notified, session_id at least do MD5 processing

Package Mainimport ("Flag" "FMT" "Net/http" "Code.google.com/p/go.net/websocket") var port *in t = flag. Int ("P", 443, "Port to listen.") Create a global map that can be sess_id,value as a WS array (pointer) var Conns = make (map[string][]*websocket. Conn)//type Msg struct {//Sender string//Receiver string//Command string//Data Map (String) interface{}//}//Jsonserver echoes back JSON string sent from client using WebSocket. Json.func Server (WS *websocket. Conn) {defer ws. Close () Req: = ws. Request () req. Parseform ()//client: = req. Formvalue ("Client") sess_id: = req.        Formvalue ("sess_id"); Ver: = req.                Formvalue ("ver")//other places to initiate a notification request, processing as required//registration connection If client, OK: = conns[sess_id];!ok { CONNS[SESS_ID] = []*websocket.         CONN{WS}} else {conns[sess_id] = append (client, WS)}//ws_list, _: = conns[sess_id] WS_LIST[1] = ws//defer Delete (Conns, Sess_ID) for {//Receive receives a text message serialized T as JSON. var msg map[string]interface{} ERR: = WebSocket. Json. Receive (WS, &MSG) if err! = Nil {fmt. Println (err) break} fmt.                Printf ("recv:% #v \ n", msg)//Send send a text message serialized T as JSON. var receiver string for k,v: = Range msg {if k = = "receiver" {R Eceiver = V. (string)}} if receiver_ws_list, OK: = Conns[receiver]; OK {//fmt. Printf ("Sess client count:% #i \ n", Len (receiver_ws_list)) for _, Receiver_ws: = Range receiver_ws_l ist {err = WebSocket. Json.                                       Send (RECEIVER_WS, msg) if (err! = nil) { Fmt.                                Println ("Failed to send!") }} FMT.                Println ("sended!") } If Err! = Nil {fmt. Println (err) break} fmt.                Printf ("send:% #v \ n", msg)} my_ws_list, _: = conns[sess_id] for I, MY_WS: = Range My_ws_list {                        if My_ws = = ws {CONNS[SESS_ID] = append (My_ws_list[:i], my_ws_list[i+1:] ...) Fmt. PRINTF ("A Client Removed\n")}}//remove ws form slice FMT. PRINTF ("A client closed\n")}func Main () {flag. Parse () http. Handle ("/", WebSocket. Handler (server)) FMT. Printf ("http://localhost:%d/\n", *port) Err: = http. Listenandserve (FMT. Sprintf (":%d", *port), 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.