Introduction

There are two ways to communicate between the web client and the server. One is to use HTTP requests to request data from the server. The disadvantage of this kind of request is that only the client can pull the server-side data, and only polling can be performed.

Another way is to use WebSocket to establish a channel between the client and the server, so that the server can directly push messages to the client, avoiding the client from frequently pulling server-side data and causing server-side pressure.

The dart:html package contains the related operations of WebSockets, let's take a look.

dart: WebSockets in html

WebSocket uses ws and wss as URI markers. Among them, ws means websocket, and wss means WebSocket Secure.

WebSocket can be divided into two parts: client and server. The WebSocket object provided in dart:html contains the logic of the client.

Let's first look at the definition of the WebSocket class:

@SupportedBrowser(SupportedBrowser.CHROME)
@SupportedBrowser(SupportedBrowser.FIREFOX)
@SupportedBrowser(SupportedBrowser.IE, '10')
@SupportedBrowser(SupportedBrowser.SAFARI)
@Unstable()
@Native("WebSocket")
class WebSocket extends EventTarget

You can see that it inherits from EventTarget and supports browsers such as chrome, firfox, IE10 and Safari.

Create a WebSocket

There are two ways to create WebSocket, the first is with protocol, the other is without protocol:

  factory WebSocket(String url, [Object? protocols]) {
    if (protocols != null) {
      return WebSocket._create_1(url, protocols);
    }
    return WebSocket._create_2(url);
  }

The protocols here refer to the sub-protocols under the webSocket protocol framework, which represent the format of the message, such as using soap or wamp.

The sub-protocol is a protocol developed on the basis of the WebSocket protocol, which is mainly used for the processing of specific scenarios. It is a more stringent specification established on top of the WebSocket protocol.

Let's look at the simplest code for creating WebSocket:

 var webSocket = new WebSocket('ws://127.0.0.1:1337/ws');

Above, if the server exists, a WebSocket connection will be successfully established.

WebSocket status

WebSocket has four states, namely closed, closing, connecting and open, which are all defined as static and can be directly referenced:

  static const int CLOSED = 3;

  static const int CLOSING = 2;

  static const int CONNECTING = 0;

  static const int OPEN = 1;

Send a message

WebSocket in dart defines the method of sending messages in 5:

  void send(data) native;

  void sendBlob(Blob data) native;

  void sendByteBuffer(ByteBuffer data) native;

  void sendString(String data) native;

  void sendTypedData(TypedData data) native;

WebSocket supports sending [Blob], [ByteBuffer], [String] or [TypedData] these four data types.

If you use send(data) directly, different sending methods will be selected according to the specific type of data.

So we can send data like this:

 if (webSocket != null && webSocket.readyState == WebSocket.OPEN) {
        webSocket.send(data);
      } else {
        print('webSocket连接异常!');
      }

Handling WebSocket events

The WebSocket client in dart can handle various events in WebSocket. There are 4 types of events defined in webSocket, as shown below:

  Stream<CloseEvent> get onClose => closeEvent.forTarget(this);

  Stream<Event> get onError => errorEvent.forTarget(this);

  Stream<MessageEvent> get onMessage => messageEvent.forTarget(this);

  Stream<Event> get onOpen => openEvent.forTarget(this);

onOpen deals with connection establishment events, onClose deals with connection closing events, onMessage deals with receiving message events, and onError deals with exception handling events.

Give an example of message processing:

 webSocket.onMessage.listen((MessageEvent e) {
        receivedData(e.data);
      });
 

Summarize

WebSocket is a very convenient and real-time communication method between client and server. You can try to use it more.

This article has been included in http://www.flydean.com/22-dart-websockets/

The most popular interpretation, the most profound dry goods, the most concise tutorial, and many tips you don't know are waiting for you to discover!

Welcome to pay attention to my official account: "programs, those things", know the technology, know you better!


flydean
890 声望437 粉丝

欢迎访问我的个人网站:www.flydean.com