websockets_将WebSockets与Node.js结合使用

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。

Browser support for WebSockets

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中实现WebSockets服务器 (Implement a WebSockets server in Node.js)

ws is a popular WebSockets library for Node.js.

wsNode.js的流行WebSockets库。

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在两个后端服务之间进行通信。

Easily install it using

使用轻松安装

yarn init
yarn add 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

翻译自: https://flaviocopes.com/node-websockets/

websockets

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值