This is a creation in Article, where the information may have evolved or changed.
This app demonstrates how to use the Google Go language and HTML5 WebSocket to implement a simple Web-based chat program.
is the chat app:
You can enter the email to join the chat room, we will get the corresponding user name and avatar from Gravatar, when you are chatting, you can see the other person's name and avatar in the chat room on the right side of the screen. You can enter information to chat with them.
Now, let's take a look at how to implement such a program.
Server-side
First we need a chat room engine called activeroom as the core of the entire application. The engine will be defined in the code below, and when the program main function starts, it initializes a chat room engine instance and acts as a global variable.
The running instance is used to maintain all websocket connections and process the received messages. Once a new message is received through the broadcast channel, it sends the message to all connected send channels.
Message is the basic data type of server and client data interaction, here we define two message types, one is text message, the other is real-time user online status.
Type activeroom struct { onlineusers map[string]*onlineuser broadcast Chan Message closesign Chan bool}type Message struct { mtype string textmessage textmessage userstatus userstatus}func (This *activeroom) the run () {for { Select {case b: = <-this. Broadcast: for _, Online: = Range this. onlineusers { online. Send <-b } case c: = <-this. Closesign: If c = = true { Close (this. Broadcast) close (this. closesign) return } } }
The Onlineuser class represents a user who successfully connects to a chat room, maintains a pointer to the Activeroom instance, websocket connection between the server and the client, and includes the user chatting and the communication channel of Go.
Onlineuser defines two pointer methods
Pushtoclient:
The messages are read from the Send channel and then pushed through WebSocket to the client.
Pullfromclient:
Reads a message from the client and sends it to the running Activeroom instance.
These two methods use a "for" statement to wait for a new message unless the WebSocket connection is interrupted.
Type onlineuser struct { inroom *activeroom Connection *websocket. Conn UserInfo *user Send Chan Message}func (this *onlineuser) pullfromclient () {for { var Content string Err: = WebSocket. Message.receive (this. Connection, &content) if err! = Nil { return } m: = message{ Mtype:text_mtype, textmessage:textmessage{ Userinfo:this. UserInfo, Time : humancreatedat (), content: content, }, } this . Inroom.broadcast <-m }}func (this *onlineuser) pushtoclient () {for B: = Range this. Send { Err: = WebSocket. Json. Send (this. Connection, B) if err! = nil {break }} }
Let's take a look at the program flow, BuildConnection where the function is registered as a WebSocket connected processor in the main function:
http. Handle ("/chat", WebSocket. Handler (Wscon. Buildconnection))
When there is a WebSocket connection request, the function will do some initialization work to process the new connection:
Func buildconnection (ws *websocket. Conn) { email: = ws. Request (). Url. Query (). Get ("email") onlineuser: = &onlineuser{ inroom: runningactiveroom, connection:ws, Send: Make (Chan Message, UserInfo: &user{ Email: Email, Name: strings. Split (email, "@") [0], gravatar:libs. Urlsize (e-mail), }, } runningactiveroom.onlineusers[email] = Onlineuser m: = message{ Mtype:status_mtype, userstatus:userstatus{ Users:runningActiveRoom.GetOnlineUsers (), }, } runningactiveroom.broadcast <-m Go onlineuser.pushtoclient () onlineuser.pullfromclient () Onlineuser.killuserresource ()}
Client
The last part is the implementation of the client, which is implemented using JavaScript. It opens a new websocket connection to the chat server, and registers a callback function for processing messages from the server side. You will find that conn.onmessage will be called when the connection receives a new message. Now all you have to do is hand over the received message to the corresponding JavaScript function to handle it:
if (window["WebSocket"]) { conn = new WebSocket ("ws://{{. websockethost}}/chat?email={{. Email}} "); Conn.onopen = function () {}; Conn.onmessage = function (evt) { var data = Json.parse (evt.data); Switch (data. Mtype) {case "Text_mtype": addmessage (data. TextMessage) break ; Case "Status_mtype": updateusers (data. UserStatus) break ; Default: } }; Conn.onerror = function () { errormessage ("<strong> an error just occured.<strong>") }; Conn.onclose = function () { errormessage ("<strong>connection closed.<strong>") };} else { errormessage ("Your browser does not support WebSockets.");
If you are interested in this application, you can get the entire application source code: gochatting.
English original, Oschina original translation
Transferred from: http://www.oschina.net/question/12_63247?from=20120805