当前位置:网站首页>[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语言框架.
边栏推荐
- Interface test advanced interface script using -apipost (pre/post execution script)
- CAS:2055042-70-9_N-(叠氮基-PEG4)-生物素
- 请问下在datastream中用flinkcdc怎么设置jdbc的参数useSSL=false呀
- Intelligent bid strategy how to affect advertising effectiveness?
- 003-序列图(一)
- MySql主要性能指标说明
- CEO对今天的CIO们真正的要求是什么?
- 120Hz OLED拒绝“烧屏”!华硕无双全能轻薄本
- 「POJ 3666」Making the Grade 题解(两种做法)
- VoLTE基础自学系列 | 3GPP规范解读之Rx接口(上集)
猜你喜欢
选择是公有云还或是私有云,这很重要吗?
Keras deep learning combat (17) - image segmentation using U-Net architecture
Redis persistence mechanism
[教你做小游戏] 斗地主的手牌,如何布局?看25万粉游戏区UP主怎么说
我们用48h,合作创造了一款Web游戏:Dice Crush,参加国际赛事
Keras深度学习实战(17)——使用U-Net架构进行图像分割
云渲染的应用正在扩大,越来越多的行业需要可视化服务
魔方电池如何“躺赢”?解锁荣威iMAX8 EV“头等舱”安全密码
漫谈测试成长之探索——测试文档
罗克韦尔Rockwell Automation EDI 项目
随机推荐
工业基础类—利用xBIM提取IFC几何数据
flask生成路由的2种方式和反向生成url
2022-08-09 Study Notes day32-IO Stream
一颗完整意义的LPWAN SOC无线通信芯片——ASR6601
Keras深度学习实战(17)——使用U-Net架构进行图像分割
openssl查看证书信息
ARouter使用自定义注解处理器,自动生成跳转Activity的代码,避免手动填写和管理path
TikTok选品有什么技巧?
Keras deep learning combat (17) - image segmentation using U-Net architecture
mysql 中大小写问题
JVM基本结构
flask装饰器版登录、session
dumpsys meminfo 详解
[Image segmentation] Image segmentation based on cellular automata with matlab code
Biotin-PEG4-IC(TFP ester/amine/NHS Ester/azide)特性分享
补坑求逆序对
第15章_锁
2022-08-09 学习笔记 day32-IO流
新建离线同步节点时选择数据去向-表时报错,数据库类型是adb pg,怎么办?
MySql main performance indicators description