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

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

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, browsers and servers only need to do a handshake, and then a fast channel is formed between the browser and the server. The data can be transmitted to each other directly between the two.
Reference:
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 run

Code:
Https://github.com/golang-samples/websocket
Server code: Eventually, it hangs on the HTTP server.

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())    }}

Client WebSocket 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}

The 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. The interesting thing is that if both the client and the server are written with go, the object is WebSocket. function calls are all the same, except that you write 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!

Developing WebSocket with Golang is straightforward.
Very convenient, because Nodejs server when the server load is suddenly high, and the Nodejs library is very miscellaneous and many, can be more difficult to solve.
I'm still more inclined to develop with Golang.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.