当前位置:网站首页>[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语言框架.
边栏推荐
猜你喜欢
宝塔部署flask项目
【深度学习前沿应用】图像风格迁移
消息队列初见:一起聊聊引入系统mq 之后的问题
ARouter使用自定义注解处理器,自动生成跳转Activity的代码,避免手动填写和管理path
如何通过JMobile软件实现虹科物联网HMI/网关的报警功能?
钻石价格预测的ML全流程!从模型构建调优道部署应用!
入门:人脸专集2 | 人脸关键点检测汇总(文末有相关文章链接)
QoS服务质量七交换机拥塞管理
[Teach you how to do mini-games] How to lay out the hands of Dou Dizhu?See what the UP master of the 250,000 fan game area has to say
set和map使用讲解
随机推荐
补坑简单图论题
6-10 二分查找(20分)
stm32中的CAN通讯列表模式配置解析与源码
2022-08-09 Study Notes day32-IO Stream
servlet映射路径匹配解析
钻石价格预测的ML全流程!从模型构建调优道部署应用!
Redis 持久化机制
Keras深度学习实战(17)——使用U-Net架构进行图像分割
ARouter使用自定义注解处理器,自动生成跳转Activity的代码,避免手动填写和管理path
西安Biotin-PEG8-IA_IA-PEG8-生物素供应商
The servlet mapping path matching resolution
企业即时通讯是什么?可以应用在哪些场景?
搭载2.8K 120Hz OLED华硕好屏 无畏Pro15 2022锐龙版屏开得胜
关于npm/cnpm/npx/pnpm与yarn
[教你做小游戏] 斗地主的手牌,如何布局?看25万粉游戏区UP主怎么说
postgis空间数据导入及可视化
阿里云贾朝辉:云 XR 平台支持彼真科技呈现国风科幻虚拟演唱会
今日份bug,点击win10任务栏视窗动态壁纸消失的bug,暂未发现解决方法。
redis.exceptions.DataError: Invalid input of type: ‘dict‘. Convert to a byte, string or number first
状态压缩dp蒙德里安的梦想