websockets_WebSockets简介
websockets
WebSockets are an alternative to HTTP communication in Web Applications.
WebSocket是Web应用程序中HTTP通信的替代方法。
They offer a long lived, bidirectional communication channel between client and server.
它们在客户端和服务器之间提供了长期的双向通信通道。
Once established, the channel is kept open, offering a very fast connection with low latency and overhead.
建立通道后,通道将保持打开状态,从而提供非常快速的连接,并具有较低的延迟和开销。
浏览器对WebSocket的支持 (Browser support for WebSockets)
WebSockets are supported by all modern browsers.
所有现代浏览器都支持WebSocket。
WebSockets与HTTP有何不同 (How WebSockets differ from HTTP)
HTTP is a very different protocol, and also a different way of communicate.
HTTP是一个非常不同的协议,也是一种不同的通信方式。
HTTP is a request/response protocol: the server returns some data when the client requests it.
HTTP是一个请求/响应协议:服务器在客户端请求时返回一些数据。
With WebSockets:
使用WebSockets:
the server can send a message to the client without the client explicitly requesting something
服务器可以向客户端发送消息,而无需客户端明确请求
the client and the server can talk to each other simultaneously
客户端和服务器可以同时对话
very little data overhead needs to be exchanged to send messages. This means a low latency communication.
发送消息所需的数据开销很少 。 这意味着低延迟的通信 。
WebSockets are great for real-time and long-lived communications.
WebSockets非常适合实时和长期通信。
HTTP is great for occasional data exchange and interactions initiated by the client.
HTTP非常适合客户端偶尔进行的数据交换和交互。
HTTP is much simpler to implement, while WebSockets require a bit more overhead.
HTTP的实现要简单得多 ,而WebSockets需要更多的开销。
安全的WebSocket (Secured WebSockets)
Always use the secure, encrypted protocol for WebSockets, wss://.
始终对WebSocket使用安全的加密协议wss:// 。
ws:// refers to the unsafe WebSockets version (the http:// of WebSockets), and should be avoided for obvious reasons.
ws://是指不安全的WebSockets版本(WebSockets的http:// ),出于明显的原因应避免使用。
创建一个新的WebSockets连接 (Create a new WebSockets connection)
const url = 'wss://myserver.com/something'
const connection = new WebSocket(url)
connection is a WebSocket object.
connection是一个WebSocket对象。
When the connection is successfully established, the open event is fired.
成功建立连接后,将触发open事件。
Listen for it by assigning a callback function to the onopen property of the connection object:
通过为connection对象的onopen属性分配一个回调函数来监听它:
connection.onopen = () => {
//...
}
If there’s any error, the onerror function callback is fired:
如果有任何错误,则会触发onerror函数回调:
connection.onerror = (error) => {
console.log(`WebSocket error: ${error}`)
}
使用WebSockets将数据发送到服务器 (Sending data to the server using WebSockets)
Once the connection is open, you can send data to the server.
打开连接后,您可以将数据发送到服务器。
You can do so conveniently inside the onopen callback function:
您可以在onopen回调函数中方便地执行此操作:
connection.onopen = () => {
connection.send('hey')
}
使用WebSocket从服务器接收数据 (Receiving data from the server using WebSockets)
Listen with a callback function on onmessage, which is called when the message event is received:
使用onmessage上的回调函数进行侦听,该函数在onmessage message事件时调用:
connection.onmessage = (e) => {
console.log(e.data)
}
在Node.js中实现服务器 (Implement a server in Node.js)
ws is a popular WebSockets library for Node.js.
We’ll use it to build a WebSockets server. It can also be used to implement a client, and use WebSockets to communicate between two backend services.
我们将使用它来构建WebSockets服务器。 它还可以用于实现客户端,并使用WebSocket在两个后端服务之间进行通信。
Install it using npm:
使用npm安装它:
npm init
npm install ws
The code you need to write is very little:
您需要编写的代码很少:
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 8080 })
wss.on('connection', (ws) => {
ws.on('message', (message) => {
console.log(`Received message => ${message}`)
})
ws.send('ho!')
})
This code creates a new server on port 8080 (the default port for WebSockets), and adds a callback function when a connection is established, sending ho! to the client, and logging the messages it receives.
此代码在端口8080(WebSocket的默认端口)上创建一个新服务器,并在建立连接时添加回调函数,发送消息ho! 发送给客户端,并记录其收到的消息。
查看有关Glitch的实时示例 (See a live example on Glitch)
Here is a live example of a WebSockets server: https://glitch.com/edit/#!/flavio-websockets-server-example
这是一个WebSockets服务器的实时示例: https ://glitch.com/edit/#!/flavio-websockets-server-example
Here is a WebSockets client that interacts with the server: https://glitch.com/edit/#!/flavio-websockets-client-example
这是一个与服务器交互的WebSockets客户端: https ://glitch.com/edit/#!/flavio-websockets-client- example
调试WebSocket (Debugging websockets)
Chrome and Firefox have a handy way to visualize all the information that is sent through WebSockets. Their DevTools support is always improving. Firefox at the time of writing has the most useful and informative debugging tool.
Chrome和Firefox提供了一种方便的方法来可视化通过WebSockets发送的所有信息。 他们的DevTools支持始终在提高。 撰写本文时,Firefox具有最有用,最有用的调试工具。
In both, you look into the Network panel and choose WS to filter only WebSockets connections.
在这两种方法中,您都需要查看“网络”面板,然后选择“ WS”以仅过滤WebSockets连接。
I took these screenshots of Firefox (Developer Edition) in action:
我拍摄了以下Firefox(开发人员版)的屏幕截图:
The Firefox DevTools can do much more than what I showed. In the example I used to test, I’m just sending a string, but you can inspect any data that’s sent in a more organized fashion:
Firefox DevTools可以做的比我展示的要多得多。 在我用来测试的示例中,我只是发送一个字符串,但是您可以检查以更有条理的方式发送的任何数据:
Check out this post on Mozilla Hacks to know more about how to use this tool.
查看有关Mozilla Hacks的文章,以了解更多有关如何使用此工具的信息。
Here is a screenshot of Chrome, which hopefully will improve its WebSockets debugging tools soon:
这是Chrome的屏幕截图,希望可以很快改进其WebSockets调试工具:
websockets
更多推荐
所有评论(0)