【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
		}

	}

}
相关推荐
花酒锄作田8 小时前
Gin 框架中的规范响应格式设计与实现
golang·gin
郑州光合科技余经理11 小时前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12311 小时前
matlab画图工具
开发语言·matlab
dustcell.12 小时前
haproxy七层代理
java·开发语言·前端
norlan_jame12 小时前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone12 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ40220549612 小时前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月12 小时前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_5312371713 小时前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian13 小时前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript