Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Q
qiuxu_code
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Commits
Issue Boards
Open sidebar
邱旭
qiuxu_code
Commits
833de141
Commit
833de141
authored
Jun 21, 2021
by
邱旭
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
默认变更列表
parent
08f2679a
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
48 additions
and
0 deletions
+48
-0
02.井子棋对战版-联机功能.md
doc/02.井子棋对战版-联机功能.md
+48
-0
No files found.
doc/02.井子棋对战版-联机功能.md
View file @
833de141
# 02.联机功能 - 井子棋对战版
## 介绍 `WebSocket`
很多网站为了实现推送技术,所用的技术都是轮询。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP请求,然后由服务器返回最新的数据给客户端的浏览器。这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。
而比较新的技术去做轮询的效果是Comet。这种技术虽然可以双向通信,但依然需要反复发出请求。而且在Comet中,普遍采用的长链接,也会消耗服务器资源。
在这种情况下,HTML5定义了WebSocket协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。
## 如何创建 `WebSocket` 服务
-
创建一个
`NodeJS`
应用
-
安装
`nodejs-websocket`
-
创建
`WebSocket`
服务
在
`NodeJS`
中创建
`WebSocket`
服务
```
shell
npm init
npm
install
nodejs-websocket
```
创建server.js
```
javascript
const
ws
=
require
(
"nodejs-websocket"
);
const
server
=
ws
.
createServer
((
conn
)
=>
{
console
.
log
(
conn
.
key
+
"建立连接"
);
conn
.
on
(
"text"
,
(
msg
)
=>
{
console
.
log
(
conn
.
key
+
"建立连接"
);
});
// 关闭连接
conn
.
on
(
"close"
,
(
code
,
reason
)
=>
{
console
.
log
(
conn
.
key
+
"关闭连接"
);
});
// 异常关闭
conn
.
on
(
"error"
,
(
code
,
reason
)
=>
{
console
.
log
(
conn
.
key
+
"异常关闭"
);
});
});
server
.
listen
(
3001
,
"0.0.0.0"
,
()
=>
{
console
.
log
(
"服务启动完毕"
);
});
```
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment