Skip to content

Commit 4d44d3e

Browse files
committed
fix: Fixed an error when sending a Uint8Array from write()
1 parent ecf2468 commit 4d44d3e

File tree

2 files changed

+20
-11
lines changed

2 files changed

+20
-11
lines changed

examples/tcpsockets/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"dependencies": {
1515
"react": "16.9.0",
1616
"react-native": "0.61.4",
17-
"react-native-tcp-socket": "^3.2.6"
17+
"react-native-tcp-socket": "^3.2.8"
1818
},
1919
"devDependencies": {
2020
"@babel/core": "^7.7.2",

src/TcpSocket.js

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,9 @@ export default class TcpSocket {
222222
}
223223

224224
/**
225+
* Sends data on the socket. The second parameter specifies the encoding in the case of a string — it defaults to UTF8 encoding.
226+
*
227+
* The optional callback parameter will be executed when the data is finally written out, which may not be immediately.
225228
*
226229
* @param {string | Buffer | Uint8Array} buffer
227230
* @param {BufferEncoding} [encoding]
@@ -232,18 +235,10 @@ export default class TcpSocket {
232235
if (this._state === STATE.DISCONNECTED) throw new Error('Socket is not connected.');
233236

234237
callback = callback || (() => {});
235-
let str;
236-
if (typeof buffer === 'string') str = Buffer.from(buffer, encoding).toString('base64');
237-
else if (Buffer.isBuffer(buffer)) str = buffer.toString('base64');
238-
else if (buffer instanceof Uint8Array || Array.isArray(buffer)) str = Buffer.from(buffer);
239-
else
240-
throw new TypeError(
241-
`Invalid data, chunk must be a string or buffer, not ${typeof buffer}`
242-
);
243-
238+
const generatedBuffer = this._generateSendBuffer(buffer, encoding);
244239
Sockets.write(
245240
this._id,
246-
str,
241+
generatedBuffer.toString('base64'),
247242
/**
248243
* @param {string} err
249244
*/
@@ -255,6 +250,20 @@ export default class TcpSocket {
255250
);
256251
}
257252

253+
/**
254+
* @param {string | Buffer | Uint8Array} buffer
255+
* @param {BufferEncoding} [encoding]
256+
*/
257+
_generateSendBuffer(buffer, encoding) {
258+
if (typeof buffer === 'string') return Buffer.from(buffer, encoding);
259+
else if (Buffer.isBuffer(buffer)) return buffer;
260+
else if (buffer instanceof Uint8Array || Array.isArray(buffer)) return Buffer.from(buffer);
261+
else
262+
throw new TypeError(
263+
`Invalid data, chunk must be a string or buffer, not ${typeof buffer}`
264+
);
265+
}
266+
258267
/**
259268
* @param {string} address
260269
*/

0 commit comments

Comments
 (0)