当前位置:网站首页>[Go WebSocket] Your first Go WebSocket server: echo server
[Go WebSocket] Your first Go WebSocket server: echo server
2022-08-10 19:03:00 【51CTO】
大家好,我是公众号「线下聚会游戏」作者,开发了 《联机桌游合集》,是个网页,可以很方便的跟朋友联机玩斗地主、五子棋等游戏.其中的核心技术就是WebSocket,快来关注专栏 《Go WebSocket》,跟我一起学习吧!
背景
上篇文章: 《为什么我选用Go重构Python版本的WebSocket服务?》,介绍了我的目标.
从这篇文章开始,我们进入实战,正式介绍Go WebSocket框架.
还没学过Go,You first look at what?
建议你花1天时间,看一下Go的原理简介、基础语法.Any tutorial can be,Well-known tutorial of the.
At least to understand:各种数据类型,控制流(for、if等)写法,弄懂channel和goroutine,如何加锁.
Must you writegoroutine和channel试一下,Understand the basic grammar.
此外,To know more about the use of the commonly used package,包括fmt、net/http.
技术选型
Face yourself don't familiar with the language and not familiar with the framework of,How to do technology selection?
I tell you a little skill,直接在Github上搜索,看StarMost of the warehouse,就可以啦~
看吧,We wentgorilla/websocket
,starSignificant differences in behind the back of a few.It is no good of tangled,Determined to use it.
新建项目
在使用GoLand时,新建Go Project会有2个选项:
We choose the first can be.
如果你没有GoLand,Can also manually create folder,在里面新建文件go.mod
(I am using the latest stable version1.18)
安装依赖
拷贝echo代码
把gorilla/websocket
的官方demo拷贝过来即可,我们慢慢分析:
You just need to copy a file,命名为server.go即可.
先尝试运行
然后浏览器打开 localhost:8080就可以了~
- 点击「Open」建立WebSocket连接
- Edit the text,按Send发送一个消息给服务器
- Server immediately respond to an identical message,这就是echo
- 点击「Close」关闭连接,之后无法Send
You all the operations will be record on the page:
当然,Also can open the developer tools,查看WebSocket连接,As you can seeHttp请求那样.This article has taught you how to useChromeThe developer of the panel caught: 《遇到表格,手动翻页太麻烦?我教你写脚本,一页展示所有数据》.
代码解读
引入依赖
定义服务地址
This is to define the server startup services address,flag
Package for processing command line arguments.Which means the service address can be through the command line parameter dynamic modification.
For example you could start:go run server.go -addr="localhost:8888"
The browser should openlocalhost:8888
来访问.
Of course if you don't need to order parameter intoaddr,Completely can delete this line,改为:
同时,还要把main函数中,最后一行改成:(删掉了addr前面的星号)
同时,把flag
Relevant rows to delete.(开头的import和main函数中的Parse)
主函数
We first introduce the main function(Although the main function definition in the back).But the main function has the role of a route,Distribute the request.我们先介绍一下,方便后续理解.
我们通过net/http
提供的能力,使用ListenAndServe
启动了Http/WebSocket服务.
其中,我们注册了2个处理函数,一个是针对path为/echo
的,这是用echo函数处理.另一个是针对path为/
的,这是用home函数处理.
When you use the browser to directly accesslocalhost:8080
时,是用了home
函数处理,一个http请求,获得一个html文件,在浏览器展示.
当你在JS中写new WebSocket('wss://localhost:8080/echo')
时,是用了echo
函数处理,一个WebSocket连接.
We then introduce the2个函数.
定义echo服务(WebSocket协议)
当客户端使用new WebSocket('ws://localhost:8080/echo')
建立时,就会开启一个goroutine,执行类似go echo(w, r)
的操作.只要这个WebSocket没有关闭,那么这个goroutine就会一直存在.
如果客户端关闭了WebSocket,Or server-side thisgoroutine执行结束了(因为有defer c.Close()
),都会导致WebSocket断掉.It is reasonable and correct,Don't write so there will be a problem.
这段echo
函数很简单,不断循环,读取消息c.ReadMessage()
,如果没消息,Will be suspended,Until there is a message.After the news,通过log
打印收到的消息,并且通过c.WriteMessage(mt, message)
The output message to the client.
这里mt
是消息类型Message Type,有2种:二进制消息、文本消息.
When the server after the output,Waiting for the client input again.
可以看到,At present is an ordered linear service:收一个、发一个、收一个、发一个.If the client sent at the same time100个,Then the server will be in accordance with this100Read a message in the order of,And in the original orderecho回去.处理完一个、To receive the next.Is the guarantee to send and receive the order of sex(The server to send the order must be compatible with the order of a closed),The downside is that can't concurrent read,性能有影响,If each processing received messages to deal with for a long time,The message behind the block、Backlog in memory.
下一篇我们会介绍chat server
,避免了这种问题. 敬请期待,可以先关注专栏、关注我噢~.
Html文本服务(Http协议)
这个服务比较简单,就是Html模板渲染.
Pay attention to a template variable:"ws://"+r.Host+"/echo"
,This template variables are actually don't need.
HTML中可以直接这么写:把ws = new WebSocket("{{.}}");
改为ws = new WebSocket('ws://' + window.location.host + '/echo');
写在最后
我是HullQin,独立开发了 《联机桌游合集》,是个网页,可以很方便的跟朋友联机玩斗地主、五子棋等游戏,不收费无广告.还独立开发了 《合成大西瓜重制版》.还开发了 《Dice Crush》参加了某个游戏制作比赛.喜欢可以关注我噢~我有空了会分享做游戏的相关技术,会在这2个专栏里分享: 《教你做小游戏》、 《极致用户体验》.
本文正在参加 技术专题18期-聊聊Go语言框架.
边栏推荐
猜你喜欢
漫谈测试成长之探索——测试文档
QoS服务质量八拥塞避免
Major upgrade of MSE Governance Center - Traffic Governance, Database Governance, Same AZ Priority
Keras深度学习实战(17)——使用U-Net架构进行图像分割
罗克韦尔Rockwell Automation EDI 项目
MSE 治理中心重磅升级-流量治理、数据库治理、同 AZ 优先
我们用48h,合作创造了一款Web游戏:Dice Crush,参加国际赛事
『牛客|每日一题』岛屿数量
servlet映射路径匹配解析
【知识分享】在音视频开发领域中SEI到底是个啥?
随机推荐
小分子PEG CAS:1352814-07-3生物素-PEG6-丙酸叔丁酯
LeetCode·283.移除零·双指针
7-2 乒乓人训练大师(双指针)
Interface test advanced interface script using -apipost (pre/post execution script)
瑞吉外卖学习笔记4
6-11 Preorder output leaf nodes (15 points)
工业基础类—利用xBIM提取IFC几何数据
选择是公有云还或是私有云,这很重要吗?
云渲染的应用正在扩大,越来越多的行业需要可视化服务
[教你做小游戏] 只用几行原生JS,写一个函数,播放音效、播放BGM、切换BGM
flask生成路由的2种方式和反向生成url
JVM内存和垃圾回收-11.执行引擎
mysql 中大小写问题
shell运算详解,看这一篇就够了!
MySQL安装步骤
多种深度模型实现手写字母MNIST的识别(CNN,RNN,DNN,逻辑回归,CRNN,LSTM/Bi-LSTM,GRU/Bi-GRU)
FPGA工程师面试试题集锦71~80
6-11 先序输出叶结点(15分)
FPGA工程师面试试题集锦81~90
799. 最长连续不重复(双指针)