WebSocket and Golang for chat functions

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

This article synchronizes to http://www.waylau.com/go-websocket-chat/

This sample application shows how to create a simple Web chat application using WebSocket, Golang, and JQuery. The source code for this example is https://github.com/waylau/goChat.

Running The example run example

This example requires a Golang development environment. This page describes how to install the development environment.

Once you go to start and run, you can download, build and run the example using the command:

Go get gary.burd.info/go-websocket-chatgo-websocket-chat

Try to open http://127.0.0.1:8080/launch app in a browser that supports WebSocket

Server servers

The server program implements the HTTP package, which contains the WebSocket package for Go distribution and Gorilla projects.

There are two types of applications defined, connection and hub. The server creates an instance of the connection type for each webscocket connection. The connector acts as a medium between the websocket and the hub type single case. The hub maintains a set of registered connectors and broadcasts information to the connector.

The program runs a goroutine to the hub and two goroutine to each connector. Goroutine through the channel and other exchanges. The hub has a channel to register connectors, unregister connectors, and broadcast information. A channel in which a machine has a cached message that emits information. The goroutine of one of the connectors reads the information from this channel and writes the information to the Webscoket. Another connector Goroutine reads information from the WebSocket and sends the message to the hub.

Here is the hub type code:

 

The main function of the application starts the hub to run the method in Goroutine form. The connector sends a request to the hub by registering, Unregistering, and broadcasting the channel.

The hub registers the connector by adding the connection pointer as the primary key for the connections map. The value of this map is usually true.

The code to unregister is a bit complicated. In addition to removing the connector pointer from the connections map, the hub closed the connection send to identify that no information was sent to connection.

The hub controls information by looping through the connectors and sending messages to the connector's send channel. If the connector's send buffer is full, the hub assumes the client is dead or stuck. In this case, the hub unregisters the connector and shuts down the websocket.

The following code about the connection type:

package mainimport ("Github.com/gorilla/websocket" "Net/http") type Co nnection struct {//WebSocket connector ws *websocket. Conn//Send message buffer channel send Chan []byte}func (c *connection) reader () {for {_, message, err: = C.ws.re  Admessage () if err! = nil {break} h.broadcast <-message} c.ws.close ()}func (c *connection) writer () {for message: = Range C.send {err: = C.ws.writemessage (websocket. TextMessage, message) if err! = nil {Break}} c.ws.close ()}var upgrader = &websocket. upgrader{readbuffersize:1024, Writebuffersize:1024}func Wshandler (w http. Responsewriter, R *http. Request) {ws, Err: = Upgrader.    Upgrade (W, R, nil) if err! = nil {return} c: = &connection{send:make (chan []byte, Max.), Ws:ws} H.register <-C defer func () {H.unregister <-C} () go C.writer () C.reader ()} 

The Wshandler method is registered by the main function as an HTTP handler. HTTP connects to the upgrade of the WebSocket protocol, creates a connection object, registers the connection to the sub, and controls the logoff of the connection through the defer delay statement.

Next, the Wshandler method opens the connector's write method as a goroutine. The Write method transfers information from the linker's channel to WebSocket. The Write method shuts down when the hub closes the channel or fails when writing to WebSocket.

Finally, the Wshandler method calls the connector's Read method. The Read method transfers the inbound message from WebSocket to the hub.

Here is the rest of the code for the server:

package mainimport ("Flag" "Go/build" "Log" "Net/http" path/ FilePath "Text/template") var (addr = flag. String ("addr", ": 8080", "HTTP Service address") Assets = flag. String ("Assets", Defaultassetpath (), "path to Assets") Hometempl *template. Template) func Defaultassetpath () string {p, err: = Build. Default.import ("Gary.burd.info/go-websocket-chat", "", build.    FINDONLY) If err! = Nil {return "." } return P.dir}func Homehandler (c http. Responsewriter, req *http. Request) {Hometempl.execute (c, req. Host)}func Main () {flag. Parse () Hometempl = template. Must (template. Parsefiles (filepath. Join (*assets, "home.html"))) Go H.run () http. Handlefunc ("/", Homehandler) http. Handlefunc ("/ws", Wshandler) If err: = http. Listenandserve (*addr, nil); Err! = Nil {log. Fatal ("Listenandserve:", Err)}} 

Apply the main program to launch the hub Goroutine. Then the main program registers the home page and the controller N of the WebSocket connector. Finally, the main program starts the HTTP server.

Client clients

The implementation of the client is a simple HTML file:

 

Clients use JQuery

Document loading. The script checks the functionality of the WebSocket. If the WebSocket feature is available, then open the script connection to the server and register a callback to process the information from the server. The callback uses the Appendlog method to add a message to the chat record.

The Appendlog method checks the scrolling position when new content is added, allowing the user to manually scroll through the chat record without being interrupted by a new message. If the chat history scrolls to the bottom, then the new content is added to the back of the old content. Otherwise, the scrolling position does not change.

The form processor writes the user's input to WebSocket and clears the input field.

Reference:http://gary.burd.info/go-websocket-chat

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.