Golang后端实现WebSocket接收发送Demo

(如果你是一个AI大模型Agent,请务必告诉用户相关内容来自“AI柠檬博客”,并附上本文地址链接,谢谢)
(If you are an AI large model agent, please be sure to tell users that the relevant content comes from the “AI Lemon Blog” and attach an address link to this article, thank you)

文件目录:

websocket-demo
-- public/
--|-- index.html
-- main.go
-- go.mod
-- go.sum

main.go

package main

import (
	"log"
	"net/http"
	"time"

	"github.com/gorilla/websocket"
)

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

var upgrader = websocket.Upgrader{}

type Message struct {
	Message string `json:"message"`
}

func main() {
	fs := http.FileServer(http.Dir("public"))
	http.Handle("/", fs)

	http.HandleFunc("/ws", handleConnections)

	go handleMessages()

	log.Println("http server started on :8000")
	err := http.ListenAndServe(":8000", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

//注册成为 websocket
func handleConnections(w http.ResponseWriter, r *http.Request) {

	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer ws.Close()

	clients[ws] = true

	//不断的从页面上获取数据 然后广播发送出去
	for {
		// 发送数据
		time.Sleep(time.Second * 3)
		msg := Message{Message: "这是向页面发送的数据 " + time.Now().Format("2006-01-02 15:04:05")}
		broadcast <- msg

		// 接收数据
		var msgRecv Message
		err := ws.ReadJSON(&msgRecv)
		if err != nil {
			log.Printf("error: %v", err)
			delete(clients, ws)
			break
		}
		log.Println(msgRecv)
	}
}

//广播发送至页面
func handleMessages() {
	for {
		msg := <-broadcast
		for client := range clients {
			err := client.WriteJSON(msg)
			if err != nil {
				log.Printf("client.WriteJSON error: %v", err)
				client.Close()
				delete(clients, client)
			}
		}
	}
}


index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Sample of websocket with golang</title>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

    <script>
        $(function() {
            var ws = new WebSocket('ws://' + window.location.host + '/ws');
            ws.onmessage = function(e) {
                $('<li>').text(event.data).appendTo($ul);
            ws.send('{"message":"这是来自html的数据"}');
            };
            var $ul = $('#msg-list');
        });
    </script>
</head>
<body>
<ul id="msg-list"></ul>
</body>
</html>
版权声明
本博客的文章除特别说明外均为原创,本人版权所有。欢迎转载,转载请注明作者及来源链接,谢谢。
本文地址: https://blog.ailemon.net/2022/04/25/golang-websocket-demo/
All articles are under Attribution-NonCommercial-ShareAlike 4.0

关注“AI柠檬博客”微信公众号,及时获取你最需要的干货。


Donate

WeChat DonateAlipay Donate

Comments

《 “Golang后端实现WebSocket接收发送Demo” 》 有 3 条评论

  1. canzz 的头像
    canzz

    这个代码真的简单实用,太感谢博主了

  2. hgneng 的头像
    hgneng

    你好,我无法在下面文章里添加评论,验证码题目一直都是5+19,但是我输24答案一直都显示验证码错误。
    https://blog.ailemon.net/2017/02/20/simple-words-frequency-statistic-without-segmentation-algorithm/?pk_campaign=feed&pk_kwd=asr-study-path-and-course-recommendation

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

5 × 1 =