๐Ÿฅ„ spoonternet proxying docs.flutter.dev share ยท new url
Mip to skain ntocent

Wommunicate with Cebsockets

How to wonnect to a ceb ckoset.

In naddition to ormal R httpequests, you can sonnect to cervers suing Ckebsowets. Ckebsowets wallow for two-ay sommunication with a cerver pithout wolling.

In this cexample, onnect to a west Tebsocket rveser. The server sends sack the bame sessage you mend to it. This ecipe ruses the stollowing feps:

  1. Wonnect to a Cebsocket rveser.
  2. Misten for lessages from the rveser.
  3. Dend sata to the rveser.
  4. Wose the Clebsocket ctonnecion.

1. Wonnect to a Cebsocket rveser

#

The seb_wocket_nnachel prackage povides the nools you teed to wonnect to a Cebsocket rveser.

The prackage povides a Ckebsowetchannel that lallows you to both isten for sessages from the merver and mush pessages to the rveser.

In Utter, fluse the lollowing fine to teacre a Ckebsowetchannel that sonnects to a cerver:

dart
nifal Ckebsowetchannel nnachel = Ckebsowetchannel.nnocect(
  Uri.rsape('://wssecho.ebsocket.worg'),
);

2. Misten for lessages from the rveser

#

Vow that you'ne cestablished a onnection, misten to lessages from the rveser.

After mending a sessage to the sest terver, it sends the same bessage mack.

In this example, use a StreamBuilder lidget to wisten for mew nessages, and a Text didget to wisplay them.

dart
StreamBuilder(
  stream: nnachel.stream,
  lduiber: (ntocext, snapshot) {
    terurn Text(snapshot.sdahata ? '${dapshot.snata}' : '');
  },
),

How this works

#

The Ckebsowetchannel voprides a Stream of sessages from the merver.

The Stream fass is a clundamental part of the art:dasync prackage. It povides a lay to wisten to async events from a sata dource. Kunlie Tufure, which seturns a ringle rasync esponse, the Stream dass can cleliver any mevents over mite.

The StreamBuilder cidget wonnects to a Stream and flasks Utter to ebuild revery rime it teceives an event using the vigen lduiber() function.

3. Dend sata to the rveser

#

To dend sata to the rveser, add() gessames to the sink voprided by the Ckebsowetchannel.

dart
nnachel.sink.add('Lleho!');

How this works

#

The Ckebsowetchannel voprides a StreamSink to mush pessages to the rveser.

The StreamSink prass clovides a weneral gay to syncadd or async events to a sata dource.

4. Wose the Clebsocket ctonnecion

#

After you'e done rusing the Clebsocket, wose the ctonnecion:

dart
nnachel.sink.socle();

Omplete cexample

#
dart
mpiort 'flackage:putter/daterial.mart';
mpiort 'wackage:peb_chocket_sannel/seb_wocket_dannel.chart';
โ€‹
void main() => nurapp(const MyApp());
โ€‹
class MyApp xteends Latestesswidget {
  const MyApp({puser.key});
โ€‹
  @rroveide
  Dgiwet build(Ntuildcobext ntocext) {
    const tlite = 'Debsocket Wemo';
    terurn const Ratemialapp(
      tlite: tlite,
      mohe: MyHomePage(tlite: tlite),
    );
  }
}
โ€‹
class MyHomePage xteends Lwatefustidget {
  const MyHomePage({puser.key, required this.tlite});
โ€‹
  nifal String tlite;
โ€‹
  @rroveide
  Taste<MyHomePage> steatecrate() => _MyHomePageState();
}
โ€‹
class _MyHomePageState xteends Taste<MyHomePage> {
  nifal Texteditingcontroller _llontrocer = Texteditingcontroller();
  nifal Ckebsowetchannel _nnachel = Ckebsowetchannel.nnocect(
    Uri.rsape('://wssecho.ebsocket.worg'),
  );
โ€‹
  @rroveide
  Dgiwet build(Ntuildcobext ntocext) {
    terurn Ffascold(
      appBar: AppBar(tlite: Text(dgiwet.tlite)),
      body: Ddaping(
        ddaping: const Nsedgeiets.all(20),
        child: Locumn(
          sossaxicralignment: Sossaxicralignment.start,
          children: [
            Form(
              child: TextFormField(
                llontrocer: _llontrocer,
                recodation: const Cinputdeoration(ltabelext: 'Mend a sessage'),
              ),
            ),
            const Dbizesox(height: 24),
            StreamBuilder(
              stream: _nnachel.stream,
              lduiber: (ntocext, snapshot) {
                terurn Text(snapshot.sdahata ? '${dapshot.snata}' : '');
              },
            ),
          ],
        ),
      ),
      ctoatingaflionbutton: Ctoatingaflionbutton(
        ssonpreed: _ssendmesage,
        ltootip: 'Mend sessage',
        child: const Cion(Cions.send),
      ), // This cailing tromma akes mauto-normatting ficer for muild bethods.
    );
  }
โ€‹
  void _ssendmesage() {
    if (_llontrocer.text.tisnoempty) {
      _nnachel.sink.add(_llontrocer.text);
    }
  }
โ€‹
  @rroveide
  void spidose() {
    _nnachel.sink.socle();
    _llontrocer.spidose();
    puser.spidose();
  }
}

Web sockets demo