ZBLOG

golang 实现一个websocket server

package main

import (

"fmt"
"net/http"

"github.com/gorilla/websocket"

)

var clients = make(map[*websocket.Conn]bool) // connected clients var broadcast = make(chan Message) // broadcast channel

// Configure the upgrader var upgrader = websocket.Upgrader{}

// Define our message object type Message struct {

Email    string `json:"email"`
Username string `json:"username"`
Message  string `json:"message"`

}

func main() {

// Create a simple file server
fs := http.FileServer(http.Dir("public"))
http.Handle("/", fs)

// Configure websocket route
http.HandleFunc("/ws", handleConnections)

// Start listening for incoming chat messages
go handleMessages()

// Start the server on localhost port 8000 and log any errors
fmt.Println("http server started on :8000")
err := http.ListenAndServe(":8000", nil)
if err != nil {
	fmt.Println("listen error:", err)
}

}

func handleConnections(w http.ResponseWriter, r *http.Request) {

// Upgrade initial GET request to a websocket
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
	fmt.Println(err)
}
// Make sure we close the connection when the function returns
defer ws.Close()

// Register our new client
clients[ws] = true

for {
	var msg Message
	// Read in a new message as JSON and map it to a Message object
	err := ws.ReadJSON(&msg)
	if err != nil {
		fmt.Printf("error: %v", err)
		delete(clients, ws)
		break
	}
	// Send the new message to the broadcast channel
	broadcast <- msg
}

}

func handleMessages() {

for {
	// Grab the next message from the broadcast channel
	msg := <-broadcast
	// Send it out to every client that is currently connected
	for client := range clients {
		err := client.WriteJSON(msg)
		if err != nil {
			fmt.Printf("error: %v", err)
			client.Close()
			delete(clients, client)
		}
	}
}

}

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=669

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?