This is a creation in Article, where the information may have evolved or changed. Recently wrote a chrome websocket extension, server End with Java Netty Framework, later found Golang implementation websocket very simple, efficient, the following is an example, simple implementation of user login, broadcast, equivalent to chat room!
[Plain]View Plaincopyprint?
- Package Main
- Import (
- "Code.google.com/p/go.net/websocket"
- "Html/template"
- "Log"
- "Net/http"
- "OS"
- "Strings"
- "Time"
- )
- Const (
- LISTENADDR = "localhost:9527"//server address
- )
- VAR (
- PWD, _ = os. GETWD ()
- Roottemp = template. Must (template. Parsefiles (pwd + "/chat.html"))
- JSON = WebSocket. JSON//Codec for JSON
- Message = WebSocket. Message//codec for string, []byte
- Activeclients = Make (map[clientconn]string)//Map containing clients
- User = Make (map[string]string)
- )
- Initialize handlers and WebSocket handlers
- Func init () {
- User["AAA"] = "AAA"
- user["BBB"] = "BBB"
- user["test"] = "Test"
- user["test2"] = "test2"
- user["test3"] = "test3"
- }
- Client connection consists of the WebSocket and the client IP
- Type Clientconn struct {
- WebSocket *websocket. Conn
- ClientIP string
- }
- WebSocket server to handle chat between clients
- Func sockserver (ws *websocket. Conn) {
- var err error
- var clientmessage string
- Use []byte if WebSocket binary type is blob or Arraybuffer
- var clientmessage []byte
- Cleanup on server side
- Defer func () {
- If Err = ws. Close (); Err! = Nil {
- Log. Println ("Websocket could not be closed", err. Error ())
- }
- }()
- Client: = ws. Request (). Remoteaddr
- Log. PRINTLN ("Client connected:", client)
- SOCKCLI: = clientconn{ws, client}
- ACTIVECLIENTS[SOCKCLI] = ""
- Log. Println ("Number of clients connected:", Len (activeclients))
- For loop so the websocket stays open otherwise
- It ' ll close after one receieve and Send
- for {
- If Err = message.receive (WS, &clientmessage); Err! = Nil {
- If We cannot Read then the connection is closed
- Log. Println ("Websocket disconnected Waiting", err. Error ())
- Remove the WS client conn from our active clients
- Delete (activeclients, SOCKCLI)
- Log. Println ("Number of clients still connected:", Len (activeclients))
- Return
- }
- var Msg_arr = strings. Split (clientmessage, "|")
- If msg_arr[0] = = "Login" && len (msg_arr) = = 3 {
- Name: = Msg_arr[1]
- Pass: = Msg_arr[2]
- If pass = = User[name] {
- ACTIVECLIENTS[SOCKCLI] = Name
- If Err = Message.send (WS, "login|" +name); Err! = Nil {
- Log. Println ("Could not send Message to", client, err.) Error ())
- }
- } else {
- Log. PRINTLN ("Login faild:", Clientmessage)
- }
- } else if msg_arr[0] = = "MSG" {
- If ACTIVECLIENTS[SOCKCLI]! = "" {
- Clientmessage = "Msg|" + time. Now (). Format ("2006-01-02 15:04:05") + "" + ACTIVECLIENTS[SOCKCLI] + "said:" + msg_arr[1]
- For cs, na: = Range activeclients {
- If na! = "" {
- If Err = Message.send (Cs.websocket, clientmessage); Err! = Nil {
- Log. Println ("Could not send Message to", Cs.clientip, err.) Error ())
- }
- }
- }
- }
- }
- }
- }
- Roothandler renders the template for the root page
- Func Roothandler (w http. Responsewriter, req *http. Request) {
- ERR: = Roottemp.execute (W, LISTENADDR)
- If err! = Nil {
- http. Error (W, err. Error (), HTTP. Statusinternalservererror)
- }
- }
- Func Main () {
- http. Handlefunc ("/", Roothandler)
- http. Handle ("/socket", WebSocket. Handler (Sockserver))
- ERR: = http. Listenandserve (listenaddr, nil)
- If err! = Nil {
- Panic ("Listenandserve:" + Err. Error ())
- }
- }