【go语言实现一个webSocket的一个demo】

go语言实现一个webSocket的一个demo

前端代码

html 复制代码
<html lang="zh-CN">

<head></head>

<body>
<script type="text/javascript">
    // header('Access-Control-Allow-Origin:*');
    var sock = null;
    var wsuri = "ws://127.0.0.1:9999";

    window.onload = function () {

        console.log("onload");

        sock = new WebSocket(wsuri);

        sock.onopen = function () {
            console.log("connected to " + wsuri);
        }

        sock.onclose = function (e) {
            console.log("connection closed (" + e.code + ")");
        }

        sock.onmessage = function (e) {
            console.log("message received: " + e.data);
        }
    };

    function send() {
        var msg = document.getElementById('message').value;
        sock.send(msg);
    };
</script>
<h1>WebSocket Echo Test</h1>
<form>
    <p>
        Message: <input id="message" type="text" value="Hello, world!">
    </p>
</form>
<button onclick="send();">Send Message</button>
</body>

</html>

服务端

  • WebSocketServer.go
go 复制代码
package main

import (
	"fmt"
	"golang.org/x/net/websocket"
	"log"
	"net/http"
)

func main() {
	http.Handle("/", websocket.Handler(Echo)) //这里校验请求头的Origin字段
	if err := http.ListenAndServe("127.0.0.1:9999", nil); err != nil {
		log.Fatal("ListenAndServer: ", err)
	}
}

func Echo(ws *websocket.Conn) {
	var err error
	for {
		var reply string
		err = websocket.Message.Receive(ws, &reply)
		if err != nil {
			fmt.Println("Can't receive data...")
			break
		}
		fmt.Println("Receive back from client:" + reply)
		msg := "Receive: " + "接受到客户端的消息,ok"
		fmt.Println("Sending to client: " + msg)

		err = websocket.Message.Send(ws, msg)
		if err != nil {
			fmt.Println("发送消息失败")
			break
		}

	}

}
相关推荐
哥不想学算法4 小时前
【C++】字符串字面量拼接
开发语言·c++
gugucoding5 小时前
21. 【C语言】打包不同类型:结构体
c语言·开发语言
Brookty5 小时前
【JavaEE】线程安全(一).4:写块串行保安全、CAS
java·开发语言·java-ee·多线程·线程安全
F20226974866 小时前
西门子 PLC 与 C# 通信
开发语言·c#
gugucoding6 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
万联WANFLOW7 小时前
多分支企业组网,IP 网段到底该怎么规划
开发语言·php
阿里嘎多学长8 小时前
2026-07-07 GitHub 热点项目精选
开发语言·程序员·github·代码托管
cookies_s_s9 小时前
C++ 字符串动态创建对象 -- 工厂模式、自动注册、模板递归动态调用
服务器·开发语言·c++
盐焗鹌鹑蛋10 小时前
【C++】继承
开发语言·c++