1

When I run my code I get:

Breaking on exception: String expected

What I am trying to do is connect to my server using a websocket. However, it seems that no matter if my server is online or not the client still crashes. My code:

import 'dart:html';
WebSocket serverConn;
int connectionAttempts;
TextAreaElement inputField = querySelector("#inputField");
String key;
void submitMessage(Event e) {
  if (serverConn.readyState == WebSocket.OPEN) {
    querySelector("#chatLog").text = inputField.value;
    inputField.value = "";
  }
}

void recreateConnection(Event e) {
  connectionAttempts++;
  if (connectionAttempts <= 5) {
    inputField.value = "Connection failed, reconnecting. Attempt" + connectionAttempts.toString() + "out of 5";
    serverConn = new WebSocket("ws://127.0.0.1:8887");
    serverConn.onClose.listen(recreateConnection);
    serverConn.onError.listen(recreateConnection);
  } else {
    inputField.value = "Connections ran out, please refresh site";
  }
}

void connected(Event e) {
  serverConn.sendString(key);
  if (serverConn.readyState == WebSocket.OPEN) {
    inputField.value = "CONNECTED!";
    inputField.readOnly = false;
  }
}

void main() {
  serverConn = new WebSocket("ws://127.0.0.1:8887");
  serverConn.onClose.listen(recreateConnection);
  serverConn.onError.listen(recreateConnection);
  serverConn.onOpen.listen(connected);
  //querySelector("#inputField").onInput.listen(submitMessage);
  querySelector("#sendInput").onClick.listen(submitMessage);
}

My Dart Editor says nothing about where the problem comes from nor does it give any warning until run-time.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567

1 Answers1

1

You need to initialize int connectionAttempts; with a valid value;
connectionAttempts++; fails with an exception on null.

You also need an onMessage handler to receive messages.

serverConn.onMessage.listen((MessageEvent e) {

recreateConnection should register an onOpen handler as well. After serverConn = new WebSocket the listener registered in main() will not work

If you register a listener where only one single event is expected you can use first instead of listen

serverConn.onOpen.first.then(connected);

According to @JAre s comment.

Try to use a hardcoded string

querySelector("#chatLog").text = 'someValue';

to ensure this is not the culprit.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567