Skip to content

Commit

Permalink
Merge branch '2.0-beta' into 2.0-beta-nullsafety
Browse files Browse the repository at this point in the history
* 2.0-beta:
  fine tune document for 2.0.0-beta.0
  1. Resolved #130 Cannot connect to socket.io V3 2. Resolve #106 Can we combine emitWithBinary to emit?
  • Loading branch information
jumperchen committed Dec 21, 2020
2 parents 77128ed + 4fda796 commit b375b6e
Show file tree
Hide file tree
Showing 14 changed files with 135 additions and 101 deletions.
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
## 1.0.0-nullsafety.0
## 2.0.0-beta.1

**New Feature:**

* [#132](https://github.com/rikulo/socket.io-client-dart/issues/132) Migrating to null safety for Dart
* [#130](https://github.com/rikulo/socket.io-client-dart/issues/130) Cannot connect to socket.io V3
* [#106](https://github.com/rikulo/socket.io-client-dart/issues/106) Can we combine emitWithBinary to emit?


## 0.9.12
Expand Down
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
# socket.io-client-dart

Port of awesome JavaScript Node.js library - [Socket.io-client v2.0.1](https://github.com/socketio/socket.io-client) - in Dart
Port of awesome JavaScript Node.js library - [Socket.io-client v2.0.1~v3.0.3](https://github.com/socketio/socket.io-client) - in Dart

### Version info:

| socket.io-client-dart | Socket.io Server
-------------------|----------------
`v0.9.*` ~ `v1.* ` | `v2.*`
`v2.*` | `v3.*`

## Usage

Expand Down
9 changes: 8 additions & 1 deletion example/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
# socket.io-client-dart

Port of awesome JavaScript Node.js library - [Socket.io-client v2.0.1](https://github.com/socketio/socket.io-client) - in Dart
Port of awesome JavaScript Node.js library - [Socket.io-client v2.0.1~v3.0.3](https://github.com/socketio/socket.io-client) - in Dart

### Version info:

| socket.io-client-dart | Socket.io Server
-------------------|----------------
`v0.9.*` ~ `v1.* ` | `v2.*`
`v2.*` | `v3.*`

## Usage

Expand Down
60 changes: 29 additions & 31 deletions lib/src/engine/socket.dart
Original file line number Diff line number Diff line change
Expand Up @@ -449,8 +449,9 @@ class Socket extends EventEmitter {
onHandshake(json.decode(data ?? 'null'));
break;

case 'pong':
setPing();
case 'ping':
resetPingTimeout();
sendPacket(type: 'pong');
emit('pong');
break;

Expand All @@ -468,6 +469,18 @@ class Socket extends EventEmitter {
}
}

///
///Sets and resets ping timeout timer based on server pings.
/// @api private
///
void resetPingTimeout() {
pingTimeoutTimer?.cancel();
pingTimeoutTimer =
Timer(Duration(milliseconds: pingInterval + pingTimeout), () {
onClose('ping timeout');
});
}

///
/// Called upon handshake completion.
///
Expand All @@ -483,48 +496,33 @@ class Socket extends EventEmitter {
onOpen();
// In case open handler closes socket
if ('closed' == readyState) return;
setPing();
resetPingTimeout();

// Prolong liveness of socket on heartbeat
off('heartbeat', onHeartbeat);
on('heartbeat', onHeartbeat);
// off('heartbeat', onHeartbeat);
// on('heartbeat', onHeartbeat);
}

///
/// Resets ping timeout.
///
/// @api private
void onHeartbeat(timeout) {
pingTimeoutTimer?.cancel();
pingTimeoutTimer = Timer(
Duration(milliseconds: timeout ?? (pingInterval + pingTimeout)), () {
if ('closed' == readyState) return;
onClose('ping timeout');
});
}

///
/// Pings server every `this.pingInterval` and expects response
/// within `this.pingTimeout` or closes connection.
///
/// @api private
void setPing() {
pingIntervalTimer?.cancel();
pingIntervalTimer = Timer(Duration(milliseconds: pingInterval), () {
_logger
.fine('writing ping packet - expecting pong within ${pingTimeout}ms');
ping();
onHeartbeat(pingTimeout);
});
}
// void onHeartbeat(timeout) {
// pingTimeoutTimer?.cancel();
// pingTimeoutTimer = Timer(
// Duration(milliseconds: timeout ?? (pingInterval + pingTimeout)), () {
// if ('closed' == readyState) return;
// onClose('ping timeout');
// });
// }

///
/// Sends a ping packet.
///
/// @api private
void ping() {
sendPacket(type: 'ping', callback: (_) => emit('ping'));
}
// void ping() {
// sendPacket(type: 'ping', callback: (_) => emit('ping'));
// }

///
/// Called on `drain` event
Expand Down
6 changes: 2 additions & 4 deletions lib/src/engine/transport/polling_transport.dart
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,7 @@ abstract class PollingTransport extends Transport {
};

// decode payload
PacketParser.decodePayload(data,
binaryType: socket?.binaryType != true, callback: callback);
PacketParser.decodePayload(data, socket!.binaryType).forEach(callback);

// if an event did not trigger closing
if ('closed' != readyState) {
Expand Down Expand Up @@ -185,8 +184,7 @@ abstract class PollingTransport extends Transport {
self.emit('drain');
};

PacketParser.encodePayload(packets, supportsBinary: supportsBinary != false,
callback: (data) {
PacketParser.encodePayload(packets, callback: (data) {
self.doWrite(data, callbackfn);
});
}
Expand Down
3 changes: 1 addition & 2 deletions lib/src/engine/transport/transport.dart
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,7 @@ abstract class Transport extends EventEmitter {
/// @param {String} data
/// @api private
void onData(data) {
var packet = PacketParser.decodePacket(data,
binaryType: socket?.binaryType, utf8decode: false);
var packet = PacketParser.decodePacket(data, socket!.binaryType);
onPacket(packet);
}

Expand Down
32 changes: 15 additions & 17 deletions lib/src/manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ class Manager extends EventEmitter {
var socket = engine;
subs.add(util.on(socket, 'data', ondata));
subs.add(util.on(socket, 'ping', onping));
subs.add(util.on(socket, 'pong', onpong));
// subs.add(util.on(socket, 'pong', onpong));
subs.add(util.on(socket, 'error', onerror));
subs.add(util.on(socket, 'close', onclose));
subs.add(util.on(decoder, 'decoded', ondecoded));
Expand All @@ -278,9 +278,9 @@ class Manager extends EventEmitter {
///
/// @api private
///
void onpong([_]) {
emitAll('pong', DateTime.now().millisecondsSinceEpoch - lastPing!);
}
// void onpong([_]) {
// emitAll('pong', DateTime.now().millisecondsSinceEpoch - lastPing);
// }

///
/// Called with data.
Expand Down Expand Up @@ -366,20 +366,18 @@ class Manager extends EventEmitter {
packet['nsp'] += '''?${packet['query']}''';
}

if (encoding != true) {
// encode, then write to engine with result
encoding = true;
encoder.encode(packet, (encodedPackets) {
for (var i = 0; i < encodedPackets.length; i++) {
engine.write(encodedPackets[i], packet['options']);
}
encoding = false;
processPacketQueue();
});
} else {
// add packet to the queue
packetBuffer.add(packet);
// if (encoding != true) {
// encode, then write to engine with result
// encoding = true;
var encodedPackets = encoder.encode(packet);

for (var i = 0; i < encodedPackets.length; i++) {
engine.write(encodedPackets[i], packet['options']);
}
// } else {
// add packet to the queue
// packetBuffer.add(packet);
// }
}

///
Expand Down
20 changes: 8 additions & 12 deletions lib/src/socket.dart
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,6 @@ class Socket extends EventEmitter {
emitWithAck(event, data);
}

void emitWithBinary(String event, [data]) {
emitWithAck(event, data, binary: true);
}

///
/// Emits to this client.
///
Expand All @@ -147,7 +143,7 @@ class Socket extends EventEmitter {
}

var packet = {
'type': binary ? BINARY_EVENT : EVENT,
'type': EVENT,
'data': sendData,
'options': {'compress': flags?.isNotEmpty == true && flags!['compress']}
};
Expand Down Expand Up @@ -186,13 +182,13 @@ class Socket extends EventEmitter {
_logger.fine('transport is open - connecting');

// write connect packet if necessary
if ('/' != nsp) {
if (query?.isNotEmpty == true) {
packet({'type': CONNECT, 'query': query});
} else {
packet({'type': CONNECT});
}
// if ('/' != nsp) {
if (query?.isNotEmpty == true) {
packet({'type': CONNECT, 'query': query});
} else {
packet({'type': CONNECT});
}
// }
}

///
Expand Down Expand Up @@ -242,7 +238,7 @@ class Socket extends EventEmitter {
ondisconnect();
break;

case ERROR:
case CONNECT_ERROR:
emit('error', packet['data']);
break;
}
Expand Down
17 changes: 8 additions & 9 deletions pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: socket_io_client
description: Dartlang port of socket.io-client for web, flutter, dartvm to use
version: 1.0.0-nullsafety.0
version: 2.0.0-beta-nullsafety.0
homepage: https://www.zkoss.org
repository: https://github.com/rikulo/socket.io-client-dart
issue_tracker: https://github.com/rikulo/socket.io-client-dart/issues
Expand All @@ -9,14 +9,13 @@ environment:
sdk: '>=2.12.0-0 <3.0.0'

dependencies:
socket_io_common: '^1.0.0-nullsafety.1'
js: '^0.6.3-nullsafety.3'
logging: '^1.0.0-nullsafety.0'

dependency_overrides:
logging: '^1.0.0-nullsafety.0'
socket_io_common: '^2.0.0-beta-nullsafety.0'

dev_dependencies:
socket_io: any
build_runner: any
build_web_compilers: any
test: ">=1.3.0 <2.0.0"
# build_runner: any
# build_web_compilers: any
# socket_io: any // support Socket.io v2.* only


22 changes: 14 additions & 8 deletions test/io_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,24 @@ import 'dart:async';
import 'package:socket_io_client/socket_io_client.dart' as io;

void main() {
var socket = io.io('http://localhost:3000', <String, dynamic>{
'transports': ['websocket'],
'extraHeaders': {'foo': 'bar'}
});
socket.on('connect', (_) {
print('connect');
socket.emit('msg', 'init');
var socket = io.io(
'http://localhost:3000',
io.OptionBuilder()
.setTransports(['websocket'])
// .disableAutoConnect()
.build());

// socket.connect();

socket.onConnect((_) {
socket.emit('toServer', 'init');

var count = 0;
Timer.periodic(const Duration(seconds: 1), (Timer countDownTimer) {
socket.emit('msg', count++);
socket.emit('toServer', count++);
});
});

socket.on('event', (data) => print(data));
socket.on('disconnect', (_) => print('disconnect'));
socket.on('fromServer', (_) => print(_));
Expand Down
1 change: 1 addition & 0 deletions test/server.dart → test/server.dart.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
*
* Copyright (C) 2017 Potix Corporation. All Rights Reserved.
*/
/// Socket.io-dart server does not support Socket.io v3 spec.
import 'package:socket_io/socket_io.dart';

void main() {
Expand Down
27 changes: 27 additions & 0 deletions test_nodejs/io_client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* io_client.js
*
* Purpose:
*
* Description:
*
* History:
* 2020/5/29, Created by jumperchen
*
* Copyright (C) 2020 Potix Corporation. All Rights Reserved.
*/
'use strict';
const io = require('socket.io-client');

var socket = io('http://localhost:3000', {
transports: ['websocket'],
autoConnect: false
});
socket.on('connect', function(){
console.log('connect');
socket.emit('msg', 'hi')
});
socket.connect();
socket.on('connect_error', function(){console.log('connect_error')});
socket.on('event', function(data){});
socket.on('disconnect', function(){console.log('disconnect')});
4 changes: 3 additions & 1 deletion test_nodejs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {
"socket.io": "^2.3.0"
"express": "^4.17.1",
"socket.io": "^3.0.3",
"socket.io-client": "^3.0.3"
}
}
Loading

0 comments on commit b375b6e

Please sign in to comment.