Golang (5): Write WebSocket service, client and HTML5 call

Source: Internet
Author: User

The text of this text connection is: http://blog.csdn.net/freewebsys/article/details/46882777 reprint please must indicate the source!

1. About WebSocket

HTML5 defines the WebSocket protocol to better conserve server resources and bandwidth and to achieve real-time communication.
The WebSocket protocol is also implemented in JavaEE7.
In the WebSocket API, the browser and server just need to do a handshake action. Then, a high-speed channel is formed between the browser and the server.

The two are directly capable of transmitting data to each other.


References:
Http://baike.baidu.com/link?

Url=gsdxnthdo4w0js-lqdo3vol0vdtyth7ylxv1amat5cesmign5u0sbay4fmjeqoix4vawn9e4ttit3dxv2a_kgk

2, install WebSocket

Use the Golang official NET package below the WebSocket, address:
Https://github.com/golang/net

First set the Go_path variable, refer to:
http://blog.csdn.net/freewebsys/article/details/46695513

Download NET package, install WebSocket module

#所有模块下载get github.com/golang/net#做下软连接把github目录以下的映射到golang.org下,否则其它模块如html安装不上。ln -s /usr/local/go_path/src/github.com/golang/net /usr/local/go_path/src/golang.org/x/net#安装websocket模块go install golang.org/x/net/websocket

The package structure of this module is unified into Golang.org/x/net. Imported using Import "Golang.org/x/net/websocket".

Document in: (Godoc is a very good site, all Golang documents are on top.)


Https://godoc.org/golang.org/x/net/websocket

3. Code and execution

Code:
Https://github.com/golang-samples/websocket
Server code: Finally, it hangs on the httpserver.

Package Mainimport ("Golang.org/x/net/websocket"    "FMT"    "Log"    "Net/http") func Echohandler (ws *websocket. Conn) {msg: = make ([]byte, +NErr: = ws. Read (msg)if Err! = Nil {Log. Fatal (Err)} FMT. Printf ("Receive:%s\n", Msg[:n]) send_msg: ="["+string(Msg[:n]) +"]"MErr: = ws. Write ([]byte (SEND_MSG))if Err! = Nil {Log. Fatal (Err)} FMT. Printf ("Send:%s\n", Msg[:m])}func Main () {http. Handle ("/echo", WebSocket. Handler (Echohandler)) http. Handle ("/", HTTP. Fileserver (http. Dir (".")))Err: = http. Listenandserve (": 8080", nil)if Err! = Nil {Panic ("Listenandserve:"+Err.Error())    }}

Clientwebsocket Calling code:

 PackageMainImport("Golang.org/x/net/websocket"    "FMT"    "Log")varOrigin ="http://127.0.0.1:8080/"varURL ="Ws://127.0.0.1:8080/echo"funcMain () {WS, Err: = WebSocket. Dial (URL,"", origin)ifErr! =Nil{log. Fatal (ERR)} message: = []byte("Hello, world!.") _, err = ws. Write (Message)ifErr! =Nil{log. Fatal (Err)} FMT. Printf ("Send:%s\n", message)varmsg = Make([]byte, +) m, err: = ws. Read (msg)ifErr! =Nil{log. Fatal (Err)} FMT. Printf ("Receive:%s\n", msg[:m]) ws. Close ()//Close connection}

Client uses WebSocket. Dial (URL, "", origin) makes a websocket connection, but the origin parameter is not actually called.
Use WebSocket to send and receive data.

It is interesting to assume that both the client and the server are written with go, using the WebSocket object.

function calls are the same. It's just a matter of writing a read data.

4. HTML5 call

Using jquery. Using Baidu's CDN:
http://cdn.code.baidu.com/
HTML5 page Code:

<! DOCTYPE html><html><head>    <meta charset="UTF-8"/>    <title>Sample of WebSocket with Golang</title>    <script src="Http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" ></script>    <script> $ (function   ()  { var  ws = new  We        Bsocket ( "Ws://localhost:8080/echo" ); Ws.onmessage = function   (        e)  { $ (). Text (Event.data). AppendTo ($ul);        };        var  $ul = $ ( ' #msg-list ' ); $ ( ' #sendBtn ' ). Click ( function   ()  { var  data = $ ( ' #name ' ). Val ();        Ws.send (data);      });    }); </script></head><body><input id="name" type="text"/><input type="button" id="sendbtn" value ="Send"/><ul id="Msg-list"></ul></body></html>

When the button is clicked, WebSocket receives the OnMessage event and then displays the data to the page.

The browser displays the WebSocket connection status.


5, summary

The text of this text connection is: http://blog.csdn.net/freewebsys/article/details/46882777 reprint please must indicate the source!

Using Golang to develop websocket is easy.
Very convenient. The server load is suddenly high when the server is Nodejs. and the library of Nodejs is very miscellaneous and many, it may be more troublesome to solve.


I'm still more inclined to develop with Golang.

Golang (5): Write WebSocket service, client and HTML5 call

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.