Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
net: properly account multi-byte chars in .bytesWritten
Browse files Browse the repository at this point in the history
  • Loading branch information
bnoordhuis committed Oct 15, 2011
1 parent 971c3d9 commit 6df574b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
4 changes: 2 additions & 2 deletions lib/net.js
Original file line number Diff line number Diff line change
Expand Up @@ -381,13 +381,13 @@ Socket.prototype.write = function(data, arg1, arg2) {
}
}

this.bytesWritten += data.length;

// Change strings to buffers. SLOW
if (typeof data == 'string') {
data = new Buffer(data, encoding);
}

this.bytesWritten += data.length;

// If we are still connecting, then buffer this for later.
if (this._connecting) {
this._connectQueueSize += data.length;
Expand Down
24 changes: 17 additions & 7 deletions test/simple/test-net-connect-buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ var assert = require('assert');
var net = require('net');

var tcpPort = common.PORT;
var fooWritten = false;
var dataWritten = false;
var connectHappened = false;

var tcp = net.Server(function(s) {
Expand All @@ -38,7 +38,7 @@ var tcp = net.Server(function(s) {
});

s.on('end', function() {
assert.equal('foobar', buf);
assert.equal(buf, "L'État, c'est moi");
console.log('tcp socket disconnect');
s.end();
});
Expand All @@ -63,19 +63,29 @@ tcp.listen(common.PORT, function() {

assert.equal('opening', socket.readyState);

var r = socket.write('foo', function() {
fooWritten = true;
// Write a string that contains a multi-byte character sequence to test that
// `bytesWritten` is incremented with the # of bytes, not # of characters.
var a = "L'État, c'est ";
var b = "moi";

// We're still connecting at this point so the datagram is first pushed onto
// the connect queue. Make sure that it's not added to `bytesWritten` again
// when the actual write happens.
var r = socket.write(a, function() {
dataWritten = true;
assert.ok(connectHappened);
console.error('foo written');
assert.equal(socket.bytesWritten, Buffer(a + b).length);
console.error('data written');
});
assert.equal(socket.bytesWritten, Buffer(a).length);

assert.equal(false, r);
socket.end('bar');
socket.end(b);

assert.equal('opening', socket.readyState);
});

process.on('exit', function() {
assert.ok(connectHappened);
assert.ok(fooWritten);
assert.ok(dataWritten);
});

0 comments on commit 6df574b

Please sign in to comment.