write 闲谈
问题
今天项目遇到一个问题,简化一下问题。多个client连接经过一些事件触发传输数据给main,main程序本身维护着多个server连接,其中一个server可能对应多个client。将数据写入server,一开始怀疑会不会数据混在一起的问题。后来明白了不会,驱动程序底层都是同步处理,在一次操作内连续输出,不被其它线程插入数据。
先来测一把:
//client.js
"use strict"
let net = require('net');
let stream = net.connect('/tmp/test');
let a = "";
let N = 2;
for(let i = 0;i < N;i++){
a+="a";
}
let b = "";
for(let i = 0;i < N;i++){
b+="b";
}
let c = "";
for(let i = 0;i < N;i++){
c+="c";
}
let d = "";
for(let i = 0;i < N;i++){
d+="c";
}
stream.on('drain', () => {
console.log('drain');
});
let flag = null;
flag = stream.write(a);
console.log(flag);
flag = stream.write(b);
console.log(flag);
flag = stream.write(c);
console.log(flag);
flag = stream.write(d);
console.log(flag);
//server.js
"use strict"
let net = require('net');
let server = net.createServer( (sock) => {
sock.setEncoding('hex');
sock.on('data', (data) => {
console.log('len is \t\t' + data.length);
console.log('data is \t\t' + data);
});
});
server.listen('/tmp/test', () => {
console.log('listen /tmp/test');
});
这时候server.js打印的数据是
$ node server.js
listen /tmp/test
len is 4
data is 6161
len is 12
data is 626263636363