项目作者: wangsir0624

项目描述 :
用Go语言写的websocket服务器
高级语言: Go
项目地址: git://github.com/wangsir0624/websocket.git
创建时间: 2017-09-30T10:46:12Z
项目社区:https://github.com/wangsir0624/websocket

开源协议:

下载


websocket

安装

  1. go get github.com/wangsir0624/websocket

用法

基本用法

  1. package main
  2. import (
  3. "fmt"
  4. "websocket"
  5. )
  6. func main() {
  7. //监听IP和端口
  8. server := websocket.Listen("127.0.0.1", 11111)
  9. //注册创建连接回调事件
  10. server.On("connection", func(conn *websocket.Conn) {
  11. fmt.Printf("accept the connection from %s\r\n", conn.RemoteAddr())
  12. })
  13. //注册错误回调函数
  14. server.On("error", func(conn *websocket.Conn) {
  15. fmt.Println(conn.GetErr())
  16. })
  17. //注册接受消息回调函数
  18. server.On("message", func(conn *websocket.Conn) {
  19. fmt.Printf("receive message from %s: %s\r\n", conn.RemoteAddr(), conn.GetData())
  20. conn.Send(conn.GetData())
  21. })
  22. //注册关闭连接回调函数
  23. server.On("close", func(conn *websocket.Conn) {
  24. fmt.Printf("the connection from %s was closed\r\n", conn.RemoteAddr())
  25. })
  26. //运行服务器
  27. server.Run()
  28. }

广播

对所有连接广播消息

  1. server.On("message", func(conn *websocket.Conn) {
  2. fmt.Printf("receive message from %s: %s\r\n", conn.RemoteAddr(), conn.GetData())
  3. conn.GetServer().Broadcast(conn.GetData())
  4. })

对其他连接广播消息

  1. server.On("message", func(conn *websocket.Conn) {
  2. fmt.Printf("receive message from %s: %s\r\n", conn.RemoteAddr(), conn.GetData())
  3. conn.GetServer().BroadcastToOthers(conn.GetData(), conn)
  4. //方法二
  5. conn.GetServer().BroadcastOnly(conn.GetData(), func(c *websocket.Conn) bool {
  6. return c.RemoteAddr().String() != conn.RemoteAddr().String()
  7. })
  8. //方法三
  9. conn.GetServer().BroadcastExcept(conn.GetData(), func(c *websocket.Conn) bool {
  10. return c.RemoteAddr().String() == conn.RemoteAddr().String()
  11. })
  12. })

服务器状态监控

本服务器采用HTTP协议的方式来监控服务器状态,监听端口为websocket端口加1,比如上面的例子中websocket端口为11111,那么http端口即为11112,在浏览器中输入http://127.0.0.1:11112,就可以监听服务器运行状态了