今天我在节点js中编写TCP服务器时遇到了问题...... 我需要为Windows和Android应用程序制作TCP服务器:只使用nodejs网络模块...
app in class被称为服务器类,它创建了几个Client实例。每个连接一个...... 在每个客户端实例中,我需要一个在" current"中可见的全局变量。客户端的实例...并且在所有其他实例中递归地在客户端类实例中调用。
我需要那个全局变量来保存会话内容,比如变量,对象和密钥......对于在Client类实例中调用的所有实例,所以...没有将值传递给每个新的instane ......
//app.js
var Server = require("./core/server/Server");
console.log('hi!');
console.dir("there is nothing to look at at the momment");
global.DEBUG = true;
global.NEW_GUID = require('uuid/v4');
var server = new Server()
server.start();
//server.js
const net = require('net');
const Client = require("./Client");
class Server{
constructor (port, address) {
this.port = port || 4484;
this.address = address || '127.0.0.1';
this.clients = [];
}
start(callback) {
let server = this;
server.connection = net.createServer((socket) => {
socket.setEncoding("UTF8");
let client = new Client(socket);
server.clients.push(client);
socket.on('error',(e)=>{ console.dir(e); })
socket.on('end', () => {});
});
this.connection.listen(this.port, this.address);
}
}
module.exports = Server;
//Client.js
//req some components
GLOBAL_VAR = {
login :"a",
sess_crypt: "encryption instance setuped in client",
socket:seocket
}
class Client {
constructor(socket) {
//some this vars }
async GetLogin() {
}
async GetData(d) {
}
StartDialog() {
}
serverHandler(){
console.log(`${this.name} connected.`);
//client.GetLogin();
this.socket.write("WELCOME\r\n")
this.socket.on("data", (d) => {
var ed = Buffer.from(d);
console.dir(ed.toString("UTF8"));
this.GetData(ed).then((r)=>{
if (r.cmd == "LOGIN") {
this.sth = new sth();
this.sth.sth(); // inside this you can have multiple calls of sth and i can't pass any value by parameter because of rest "old" js code what was running on RHINo Java server that i can't modifi to much
}
})
})
}
}
module.exports = Client;
///sth.js
//req some components
class sth extends other_staf{
constructor() {
this.login = GLOBAL_VAR.login
}
oninit(){
// do staf start next instance of sth()
}
sth(){
GLOBAL_VAR.socket.write(GLOBAL_VAR.sess_crypt("some request\r\n"))
this.oninit();
}
}
module.exports = sth;
答案 0 :(得分:0)
您不需要全局变量。你可以尝试这样做,在Client中定义数据就像这样
var client = new Client();
client.data.name = "client 1";
或者更好地将它传递给contructor:
var client = new Client({name: "client 1"});
并在构造函数中使用
function Client(options) {
this.data = options;
// ...
}
并将客户端对象传递给实例:
var instance = new instance(client);
并访问:
instance.client.data.name;
如果您在证明图像中的那个框是对象的内部,那么您可以使用它而不是实例和客户端。