Skip to content
go语言使用websocket

go后端代码

安装模块

go
go get "github.com/gorilla/websocket"

main.go代码如下:

go
package main

import (
	"fmt"
	"github.com/gorilla/websocket"
	"net/http"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		// 允许所有来源的WebSocket连接
		return true
	},
}

func main() {
	http.HandleFunc("/ws", wsHandle)
	err := http.ListenAndServe(":9009", nil)
	if err != nil {
		fmt.Println(err)
	}
}

func wsHandle(w http.ResponseWriter, r *http.Request) {
	// 升级为ws
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer conn.Close()
	fmt.Println("连接建立成功")
	// 循环监听客户端传来的消息
	for {
		// 读取客户端消息
		messageType, p, err := conn.ReadMessage()
		if err != nil {
			fmt.Println(err)
			return
		}

		// 处理消息
		fmt.Println("接收到客户端的消息为: ", string(p))

		// 发送消息给客户端
		err = conn.WriteMessage(messageType, p)
		//err = conn.WriteMessage(messageType, []byte("我是服务器返回的消息"))
		if err != nil {
			fmt.Println(err)
			return
		}
	}
}

运行项目(右键运行)

项目运行地址为: ws://127.0.0.1:9009/ws

前端测试demo页面代码如下

也可以使用这个网站测试webSocket代码:http://www.websocket-test.com/

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket 连接测试</title>
<style>
  #log {
    margin-top: 20px;
    border: 1px solid #ccc;
    padding: 10px;
    height: 500px;
    overflow-y: scroll;
  }
</style>
</head>
<body>

<h2>WebSocket 连接测试页面</h2>

<button id="connect">连接</button>
<input type="text" autocomplete="off" id="address" value="ws://127.0.0.1:9009/ws" placeholder="输入webSocket地址...">
<button id="disconnect" disabled>断开连接</button>
<button id="send" disabled>发送消息</button>

<input type="text" autocomplete="off" id="message" placeholder="输入消息...">
<div id="log"></div>

<script>
  var ws;
  var log = document.getElementById('log');

  function logMessage(message) {
    var p = document.createElement('p');
    p.textContent = message;
    log.appendChild(p);
    // 确保日志始终显示在底部
    log.scrollTop = log.scrollHeight;
  }

  document.getElementById('connect').addEventListener('click', function() {
    if ('WebSocket' in window) {
      ws = new WebSocket(document.getElementById('address').value);
      ws.onopen = function() {
        logMessage('已连接到WebSocket服务器。');
        document.getElementById('connect').disabled = true;
        document.getElementById('disconnect').disabled = false;
        document.getElementById('send').disabled = false;
      };
      ws.onmessage = function(event) {
        logMessage('接收到消息:' + event.data);
      };
      ws.onclose = function(event) {
        if (event.wasClean) {
          logMessage('连接已干净地关闭。');
        } else {
          logMessage('连接已断开。');
        }
        logMessage('代码:' + event.code + ', 原因:' + event.reason);
        document.getElementById('connect').disabled = false;
        document.getElementById('disconnect').disabled = true;
        document.getElementById('send').disabled = true;
      };
      ws.onerror = function(error) {
        logMessage('WebSocket错误:' + JSON.stringify(error));
      };
    } else {
      // 浏览器不支持WebSocket
      logMessage('你的浏览器不支持WebSocket。');
    }
  });

  document.getElementById('disconnect').addEventListener('click', function() {
    ws.close();
  });

  document.getElementById('send').addEventListener('click', function() {
    var message = document.getElementById('message').value;
    ws.send(message);
    logMessage('发送消息:' + message);
  });
</script>

</body>
</html>