我有一个简单的 websocket 聊天服务器,可以处理多个客户端。我使用一个数组来跟踪所有客户端,并在客户端关闭连接时对数组进行切片。
我想知道当多个客户端大约同时关闭连接时,对数组进行切片是否会导致问题。
这是代码段:
var clients = [];
var wsServer = new webSocketServer ({
httpServer: httpserver
});
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
var index = clients.push(connection) - 1;
....
connection.on('close', function(connection) {
for (var i=0; i<clients.length; i++)
if (i != index) clients[i].sendUTF('Some client has left the chat!');
//At this point some other clients may have disconnected and the above
//for-loop may be running for another connection.
clients.splice(index, 1);
//After the array has been sliced, will the for-loop for other
//connection(s) fail?
Run Code Online (Sandbox Code Playgroud)
JavaScript 是单线程的,所以是的,Array.splice线程安全。
当调用堆栈为空时,异步回调只能进入调用堆栈。因此,如果调用堆栈上有 an Array.splice,则包含 an 的另一个回调Array.splice将必须等待第一个回调完成。
const arr = [1,2,3,4];
request('http://foo.com', (err, res, body) => {
arr.splice(0, 1)
});
request('http://bar.com', (err, res, body) => {
arr.splice(0, 1)
});
Run Code Online (Sandbox Code Playgroud)
考虑上面的片段。如果这些请求同时完成(为了争论,请想象一下)。然后一个回调,或者foo.com或bar.com将进入调用堆栈。该回调中的所有同步代码都将被执行(异步调用将被执行,但回调不会被执行),并且来自其他请求的回调在调用堆栈为空之前无法被处理。所以 foo.com和bar.com回调不能同时处理。
JavaScript 是单线程的,它有一个调用栈,所以它一次只能做一件事。
| 归档时间: |
|
| 查看次数: |
1755 次 |
| 最近记录: |