Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现一个简单的websocket 的连接 #4

Open
yaogengzhu opened this issue Oct 15, 2023 · 1 comment
Open

实现一个简单的websocket 的连接 #4

yaogengzhu opened this issue Oct 15, 2023 · 1 comment

Comments

@yaogengzhu
Copy link
Member

第一步:路由注册

package ws

import (
	"ginchat/service"

	"github.com/gin-gonic/gin"
)

func WsRouter() *gin.Engine {
	r := gin.New()
	v1 := r.Group("/v1/ws")

	v1.GET("/connect", service.HandlerWs)
	return r
}

第二步实现路由方法

package service

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrade = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func HandlerWs(c *gin.Context) {
	// 升级成websocket协议
	ws, err := upgrade.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Fatalln(err, "err")
	}
	fmt.Println("ws connect success")
	// 完成时关闭连接释放资源
	defer ws.Close()

	go func() {
		// 监听连接“完成”事件,其实也可以说丢失事件
		<-c.Done()
		fmt.Println("ws lost connection")
	}()

	for {
		// 读取客户端发送过来的消息,如果没发就会一直阻塞住
		mt, message, err := ws.ReadMessage()

		if err != nil {
			fmt.Println("read error")
			fmt.Println(err)
			break
		}
		if string(message) == "ping" {
			message = []byte("恭喜您连接成功,您可以发送消息了")
		}
		// 将读取到的消息写回客户端,这里是原封不动的写回去
		fmt.Print("receive message: ", mt, "\n")
		err = ws.WriteMessage(mt, message)
		if err != nil {
			fmt.Println(err)
			break
		}

	}
}

参考文章: https://juejin.cn/post/7103737973782511646

@yaogengzhu
Copy link
Member Author

ngnix 部署时处理

  location /v1/ws/connect {
      proxy_pass http://xxxx:8888/v1/ws/connect;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "Upgrade";
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant