Go implementation WebSocket message push

Source: Internet
Author: User
Tags sendmsg

1.websocket Introduction

In the past, the browser wanted to get the server data by sending an HTTP request and then waiting for the server to respond. That is, the browser side has always been the initiator of the entire request, only if it is active, to obtain data. To allow the browser side to get real-time data on the server side, it is necessary to constantly initiate requests to the server. Although the actual data has not been obtained in most cases, this greatly increases the network pressure, and the pressure on the service side is also soaring.


Image.png

Since WebSocket is a full-duplex communication, the next communication is similar to the traditional TCP communication when the WebSocket connection is established. The client and the server can send data to each other, and there is no real-time problem.


Image.png
Image.png

2. Selection of development packages

In the Go official SDK, there is no support for WebSocket, so you must use a third-party library.
To use Golang to develop WebSocket, select Basic between X/net/websocket and Gorilla/websocket. The example in Go Web programming is used x/net/websocket as a development package, and it seems to be more official and formal. In fact, according to the feedback I received on the Internet, it is not so. x/net/websocketseemingly Bug more, and more unstable, problem solving is not timely. By contrast, gorilla/websocket it is better.
Download links and Manuals

3. Push Service Implementation

Two Handler will be registered after server startup.
websocketHandler 用于提供浏览器端发送 Upgrade 请求并升级为 WebSocket 连接。 pushHandler 用于提供外部推送端发送推送数据的请求。

Simple implementation of 3-1.GO code

Package Mainimport ("Net/http" "Log" "Github.com/gorilla/websocket") var (upgrader = WebSocket.        Upgrader {//Read storage space size readbuffersize:1024,//write storage size writebuffersize:1024,//allow cross-domain Checkorigin:func (R *http. Request) bool {return true},}) Func Wshandler (w http. Responsewriter, R *http. Request) {var (wbscon *websocket. Conn Err error data []byte]//Complete HTTP reply, drop the following parameter in Httpheader if wbscon, err = upgrader.        Upgrade (W, R, Nil); Err! = Nil {return//Get connection failed directly return} for {//can only send text, Binary type of data, underline means ignore this variable. If _, data, err = Wbscon.readmessage (); Err! = nil {goto err//Jump to close connection} if Err = WBSCON.W Ritemessage (WebSocket. TextMessage, data);    Err! = Nil {goto ERR//Send message failed, close connection}} ERR://close Connection Wbscon.close ()}func main () { This callback method HTTP is executed when there is a request to access WS. Handlefunc ("/ws", wshandler)//monitoring 127.0.0.1:7777 ERR: = http. Listenandserve ("0.0.0.0:7777", nil) if err! = Nil {log. Fatal ("Listenandserve", err. Error ())}}

3-2. Front-end Code

<! DOCTYPE html>

3-3. Results analysis

Results of the operation


Image.png

The process of interaction
1.request request, the protocol is required to be upgraded to the WebSocket parameter
When 2.response returns, returns the WebSocket parameter if successful


Image.png

The form of data transmission is to split the data into multiple frames to send and receive, this does not concern us.


Image.png
Image.png

4. Third-party resources

https://www.imooc.com/video/17599
Https://www.cnblogs.com/snowInPluto/p/8688453.html

5.PHP Frontier Learning Group: 257948349go也收

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.