我需要能够知道哪个客户端正在通过Web套接字向服务器发送请求,并将其区别于其他客户端。解决方案是客户端ID,但我不知道存储它的最佳方法,以便客户端可以将其与每个请求一起发送。
客户
var clientId = null;
if (response.method === "connect"){
clientId = response.clientId
}
我需要能够知道哪个客户端正在通过Web套接字向服务器发送请求,并将其区别于其他客户端。解决方案是客户端ID,但我不知道存储它的最佳方法,以便客户端可以将其与每个请求一起发送。
客户
var clientId = null;
if (response.method === "connect"){
clientId = response.clientId
}
You could wrap your code with an IIFE which remove the possibility to access variables in the global scope outside of the IIFE. So only the code that runs inside of this IIFE can access the
clientId
variable. But changing theclientId
from, for example, the console wouldn't change a thing.If only overwriting the variable is a problem, then you could alternatively use the Web Storage API to save the id in the browser, either permanently or until the tab has been closed. So you could store it like in the example below.
并在脚本的更下方,甚至在同一页面的另一脚本中使用以下代码,使用clientId:
因此,IIFE将无法在自己的范围之外对变量进行修改。 Web Storage API会将您的客户端ID存储在浏览器中,而不是变量中。