Golang using WebSocket

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

In the Server.go file in Google's officially maintained Code.google.com\p\go.net\websocket package, there was a description:

// handler" is a simple interface to a WebSocket browser client.
//It checks if Origin header is a valid URL by default.
//You might want to verify websocket. Conn.config (). Origin in the Func.
//If You use Server instead of Handler, you could call WebSocket. Origin and
//Check the origin in your handshake func. so, if you want to accept
//Non-browser client, which doesn ' t send Origin header, you could use Server
//. T Hat doesn ' t check origin in its handshake.

Here, handler is a simple interface for WebSocket browser clients, and by default, handler checks if origin of the header file for the HTTP request is a valid value. Finally, if you want to receive a websocket request from a non-browser client that does not have the Origin field information, you should use server, and the server will not check origin when the WebSocket handshake is in use.

Perhaps we will ask, what is the browser client, and what is non-browser client, the author of this study is not deep, just found in the development, in the go Web programming, because go itself can use template templates to push the page to the user, such as the user input 127.0.0.1 on the client : 9000, the server receives this request, will send the homepage of the website to the user (here assumes 127.0.0.1:9000/, this route corresponds to a homepage of GET request). The author thinks that the Web server program which is written by Go is the browser client which is pushed to the user . In addition to other non-push Web requests, as well as some mobile phones (andriod, iOS phones) clients send requests belong to non-browser clients.

Then we will ask, if it is a browser client, how to use handler, not the browser client, how to use the server? Here's a simple example:

First of all, the browser client's listening WebSocket programming, code examples are:

Package Main

Import (
"Bufio"
"Code.google.com/p/go.net/websocket"
"Container/list"
"FMT"
"io"
"Net/http"
)

var Connid int
var Conns *list. List

Func chatroomserver (ws *websocket. Conn) {
defer ws. Close ()

connid++
ID: = Connid

fmt. PRINTF ("Connection ID:%d\n", id)

Item: = Conns. Pushback (WS)
Conns. Remove (item)

Name: = fmt. Sprintf ("user%d", id)

SendMessage (nil, FMT. Sprintf ("Welcome%s join\n", name))

r: = bufio. Newreader (WS)

     for {
           data, err: = R.readbytes (' \ n ')
            If err! = nil {
                   fmt. PRINTF ("Disconnected ID:%d\n", id)
                   sendmessage (item, FMT. Sprintf ("%s offline\n", name))
                   break
           }

fmt. Printf ("%s:%s", name, data)

SendMessage ( Item, FMT. Sprintf ("%s\t>%s", name, data))
  }
}

func SendMessage (self *list.) Element, data string) {
     for Item: = Conns. Front (); Item! = NIL; Item = Item. Next () {
             ws, OK: = Item. Value. (*websocket. Conn)
             if!ok {
                 panic ("Item not *websocket. Conn ")
             }

if item = = Self {
continue
      }

io . WriteString (WS, Data)
  }
}

func Client (w http. Responsewriter, R *http. Request) {
         html:=  ' <!doctype html>

              

Io. WriteString (w, HTML)
}

Func Main () {
fmt . Printf (' Welcome chatroom server! ')

&NBSP;      connid = 0
       conns = list. New ()

&NBSP;      http. Handle ("/chatroom", WebSocket. Handler (chatroomserver))
       http. Handlefunc ("/", Client)
       err: = http. Listenandserve (": 9090", nil)
       if Err! = nil {
               panic ("Listenandserve:" + Err. Error ())
       }
}

Above is a complete server code for the browser client to send WebSocket, you can see, when the user request route to/, the server pushes a page to the user, this page contains the WebSocket socket, and then receive this page of the user, Can be in this page is the input information sent to the background, send the use is websocket. The main function shows how to use the WebSocket. Handler.

The following is a non-browser client's wording, here only modified the main function, in order to be able to listen to both HTTP requests and WebSocket requests, and the above, the use of a multi-way implementation, and here the WebSocket monitoring without routing, all websocket, Regardless of the number of routes, it will be listened to, the code is as follows:

Func Main () {
fmt . Printf (' Welcome chatroom server! ')

Connid = 0
Conns = list. New ()

http . Handlefunc ("/", Client)

&NBSP;      go func () {

&NBSP;              err: = http. Listenandserve (": 9090", nil)
               if Err! = nil {
                       panic ("Listenandserve:" + Err. Error ())
              }

   }
ERR: = http. Listenandserve (": 9090", WebSocket. Server{websocket. Config{},nil,chatroomserver})
If Err! = Nil {
Panic ( "Listenandserve:" + Err. Error ())
   }

}

end

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.