forked from circlecloud/tera
refactor: rewrite rpc server client
Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
parent
fd1b23a4c3
commit
b05a00f87d
@ -23,6 +23,7 @@
|
||||
"start": "node dist/run-node.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@cc-server/binding": "^0.6.1",
|
||||
"@cc-server/core": "^0.6.1",
|
||||
"@cc-server/ws": "^0.6.1",
|
||||
"bintrees": "^1.0.2",
|
||||
|
@ -22,71 +22,7 @@
|
||||
|
||||
<body>
|
||||
<div id="terminal" style="height: 100%;"></div>
|
||||
<script type="text/javascript">
|
||||
Terminal.applyAddon(fit);
|
||||
Terminal.applyAddon(attach);
|
||||
Terminal.applyAddon(fullscreen);
|
||||
var term = new Terminal({
|
||||
cursorBlink: true,
|
||||
screenKeys: true
|
||||
});
|
||||
term.open(document.getElementById('terminal'));
|
||||
term.toggleFullScreen();
|
||||
term.fit();
|
||||
|
||||
var cmd = ''
|
||||
term.on('data', (data) => {
|
||||
if (data =='\r') {
|
||||
term.writeln(data)
|
||||
if(cmd.startsWith('/')){
|
||||
args = cmd.split(' ');
|
||||
cmd = args[0].substr(1);
|
||||
switch(cmd){
|
||||
case "connect":
|
||||
if(args[1]){
|
||||
newcon(args[1])
|
||||
} else {
|
||||
newcon('/main')
|
||||
}
|
||||
break;
|
||||
case "disconnect":
|
||||
socket.close();
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
socket && socket.emit('webmsg', {cmd});
|
||||
}
|
||||
cmd = ''
|
||||
} else {
|
||||
cmd += data;
|
||||
term.write(data)
|
||||
}
|
||||
});
|
||||
|
||||
function newcon(address){
|
||||
socket = io(address,{
|
||||
path: '/ws',
|
||||
transports: ['websocket']
|
||||
});
|
||||
socket.on('connect', function(){
|
||||
term.writeln('connect')
|
||||
socket.emit('webclient',{})
|
||||
});
|
||||
socket.on('message', function(data){
|
||||
for (const line of JSON.stringify(data, undefined, 4).split('\n')){
|
||||
term.writeln(line);
|
||||
}
|
||||
});
|
||||
socket.on('disconnect', function(){
|
||||
term.reset();
|
||||
term.writeln('disconnect')
|
||||
});
|
||||
}
|
||||
window.onresize = function() {
|
||||
term.fit();
|
||||
term.scrollToBottom();
|
||||
};
|
||||
</script>
|
||||
<script src="index.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
69
public/index.js
Normal file
69
public/index.js
Normal file
@ -0,0 +1,69 @@
|
||||
Terminal.applyAddon(fit);
|
||||
Terminal.applyAddon(attach);
|
||||
Terminal.applyAddon(fullscreen);
|
||||
var term = new Terminal({
|
||||
cursorBlink: true,
|
||||
screenKeys: true
|
||||
});
|
||||
term.open(document.getElementById('terminal'));
|
||||
term.toggleFullScreen();
|
||||
term.fit();
|
||||
|
||||
var cmd = ''
|
||||
term.on('data', (data) => {
|
||||
if (data == '\r') {
|
||||
term.writeln(data)
|
||||
if (cmd.startsWith('/')) {
|
||||
args = cmd.split(' ');
|
||||
cmd = args[0].substr(1);
|
||||
switch (cmd) {
|
||||
case "connect":
|
||||
let address = args[1] || 'https://tera-ws.miaowoo.cc/web'
|
||||
term.writeln(`Connect to ${address}...`)
|
||||
newcon(address)
|
||||
break;
|
||||
case "disconnect":
|
||||
socket.close();
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
socket && socket.emit('webmsg', { cmd });
|
||||
}
|
||||
cmd = ''
|
||||
return
|
||||
}
|
||||
cmd += data;
|
||||
term.write(data)
|
||||
});
|
||||
let socket = undefined
|
||||
function newcon(address) {
|
||||
if (socket) {
|
||||
socket.close()
|
||||
}
|
||||
socket = io(address, {
|
||||
path: '/ws',
|
||||
transports: ['websocket']
|
||||
});
|
||||
socket.on('connect', function() {
|
||||
term.writeln('connect')
|
||||
socket.emit('webclient', {})
|
||||
});
|
||||
socket.on('message', function(data) {
|
||||
if (typeof data === "string") {
|
||||
term.writeln(data);
|
||||
} else {
|
||||
for (const line of JSON.stringify(data, undefined, 4).split('\n')) {
|
||||
term.writeln(line);
|
||||
}
|
||||
}
|
||||
});
|
||||
socket.on('disconnect', function() {
|
||||
term.reset();
|
||||
term.writeln('disconnect')
|
||||
});
|
||||
socket.connect()
|
||||
}
|
||||
window.onresize = function() {
|
||||
term.fit();
|
||||
term.scrollToBottom();
|
||||
};
|
@ -12,7 +12,7 @@
|
||||
import CBlock from './block-loader'
|
||||
import { RBTree } from './library'
|
||||
import { STreeBuffer } from './base';
|
||||
import { SendToWebClient } from '../rpc/server'
|
||||
import { teraManager } from '../rpc/manager'
|
||||
require('./library');
|
||||
require('./crypto-library');
|
||||
const TX_PROCESS_TIME = 100;
|
||||
@ -1352,16 +1352,16 @@ export default class CConsensus extends CBlock {
|
||||
MiningProcess(msg) {
|
||||
var BlockMining = this.GetBlock(msg.BlockNum);
|
||||
if (!BlockMining) {
|
||||
SendToWebClient({
|
||||
teraManager.SendToWebClient({
|
||||
msg: msg,
|
||||
errror: '!BlockMining'
|
||||
error: '!BlockMining'
|
||||
})
|
||||
return;
|
||||
}
|
||||
if (!BlockMining.StartMining || BlockMining.bSave) {
|
||||
SendToWebClient({
|
||||
teraManager.SendToWebClient({
|
||||
msg: msg,
|
||||
errror: `!BlockMining.StartMining ${BlockMining.StartMining} || BlockMining.bSave ${BlockMining.bSave}`
|
||||
error: `!BlockMining.StartMining ${BlockMining.StartMining} || BlockMining.bSave ${BlockMining.bSave}`
|
||||
})
|
||||
return;
|
||||
}
|
||||
@ -1404,19 +1404,19 @@ export default class CConsensus extends CBlock {
|
||||
setTimeout(() => {
|
||||
let webmsg: any = { BlockNum: msg.BlockNum }
|
||||
webmsg.Mining = {
|
||||
SeqHash: global.GetHexFromArr(BlockMining.SeqHash),
|
||||
AddrHash: global.GetHexFromArr(BlockMining.AddrHash),
|
||||
PrevHash: global.GetHexFromArr(BlockMining.PrevHash),
|
||||
TreeHash: global.GetHexFromArr(BlockMining.TreeHash),
|
||||
Hash: global.GetHexFromArr(BlockMining.Hash),
|
||||
SeqHash: global.GetHexFromArr(BlockMining.Hash)
|
||||
}
|
||||
webmsg.New = {
|
||||
Hash: global.GetHexFromArr(ValueNew.Hash),
|
||||
PowHash: global.GetHexFromArr(ValueNew.PowHash)
|
||||
PowHash: global.GetHexFromArr(BlockMining.PowHash)
|
||||
}
|
||||
Object.assign(webmsg, {
|
||||
HashCount,
|
||||
Power,
|
||||
Num: msg.Num
|
||||
Num: msg.NodeNum
|
||||
})
|
||||
SendToWebClient(webmsg)
|
||||
teraManager.SendToWebClient(webmsg)
|
||||
}, 1)
|
||||
}
|
||||
}
|
||||
|
@ -1193,10 +1193,19 @@ global.HTTPCaller.GetHistoryTransactions = function(Params) {
|
||||
|
||||
function GetCopyBlock(Block) {
|
||||
var Result: any = {
|
||||
BlockNum: Block.BlockNum, bSave: Block.bSave, TreeHash: global.GetHexFromAddres(Block.TreeHash), AddrHash: global.GetHexFromAddres(Block.AddrHash),
|
||||
PrevHash: global.GetHexFromAddres(Block.PrevHash), SumHash: global.GetHexFromAddres(Block.SumHash), SumPow: Block.SumPow, TrDataPos: Block.TrDataPos,
|
||||
TrDataLen: Block.TrDataLen, SeqHash: global.GetHexFromAddres(Block.SeqHash), Hash: global.GetHexFromAddres(Block.Hash), Power: global.GetPowPower(Block.PowHash),
|
||||
TrCount: Block.TrCount, arrContent: Block.arrContent,
|
||||
BlockNum: Block.BlockNum,
|
||||
bSave: Block.bSave,
|
||||
TreeHash: global.GetHexFromAddres(Block.TreeHash),
|
||||
AddrHash: global.GetHexFromAddres(Block.AddrHash),
|
||||
PrevHash: global.GetHexFromAddres(Block.PrevHash),
|
||||
SumHash: global.GetHexFromAddres(Block.SumHash),
|
||||
SumPow: Block.SumPow, TrDataPos: Block.TrDataPos,
|
||||
TrDataLen: Block.TrDataLen,
|
||||
SeqHash: global.GetHexFromAddres(Block.SeqHash),
|
||||
Hash: global.GetHexFromAddres(Block.Hash),
|
||||
Power: global.GetPowPower(Block.PowHash),
|
||||
TrCount: Block.TrCount,
|
||||
arrContent: Block.arrContent,
|
||||
};
|
||||
return Result;
|
||||
};
|
||||
|
@ -13,6 +13,16 @@ import "./library"
|
||||
import * as net from "net"
|
||||
import { secp256k1, RBTree } from '../core/library'
|
||||
var ConnectIDCount = 1;
|
||||
export class TeraSocket extends net.Socket {
|
||||
ConnectToServer: boolean;
|
||||
Node: CNode;
|
||||
ConnectID: string;
|
||||
WasClose: number;
|
||||
SocketStatus: number;
|
||||
Buf: Buffer;
|
||||
SocketNum: number;
|
||||
SocketPrioritet: number;
|
||||
}
|
||||
export default class CNode {
|
||||
addrStr
|
||||
ip
|
||||
@ -72,7 +82,7 @@ export default class CNode {
|
||||
CanHardTraffic
|
||||
BufWriteLength
|
||||
BufWrite
|
||||
SendPacket
|
||||
SendPacket: RBTree<any>
|
||||
ConnectCount
|
||||
TrafficArr
|
||||
SendTrafficCurrent
|
||||
@ -80,11 +90,11 @@ export default class CNode {
|
||||
ErrCount
|
||||
ErrCountAll
|
||||
SendPacketNum
|
||||
Socket
|
||||
Socket2
|
||||
Socket: TeraSocket
|
||||
Socket2: TeraSocket
|
||||
ReconnectFromServer
|
||||
SecretForReconnect
|
||||
Self
|
||||
Self: boolean
|
||||
addrStrTemp
|
||||
DoubleConnection
|
||||
PubKey
|
||||
@ -191,7 +201,7 @@ export default class CNode {
|
||||
NODE.Socket.ConnectToServer = true
|
||||
SetSocketStatus(NODE.Socket, 2)
|
||||
}
|
||||
})
|
||||
}) as TeraSocket
|
||||
SetSocketStatus(NODE.Socket, 1)
|
||||
NODE.Socket.Node = NODE
|
||||
NODE.Socket.ConnectID = "~C" + ConnectIDCount
|
||||
@ -210,7 +220,7 @@ export default class CNode {
|
||||
NODE.Socket2.ConnectToServer = true
|
||||
SetSocketStatus(NODE.Socket2, 2)
|
||||
}
|
||||
})
|
||||
}) as TeraSocket
|
||||
SetSocketStatus(NODE.Socket2, 1)
|
||||
NODE.Socket2.Node = NODE
|
||||
NODE.Socket2.ConnectID = "~R" + ConnectIDCount
|
||||
@ -286,7 +296,7 @@ export default class CNode {
|
||||
}
|
||||
else
|
||||
if (Str === "SELF") {
|
||||
NODE.Self = 1
|
||||
NODE.Self = true
|
||||
}
|
||||
else
|
||||
if (Str === "DOUBLE") {
|
||||
@ -395,7 +405,7 @@ export default class CNode {
|
||||
Node.addrArr = Buf.addrArr
|
||||
Node.addrStr = addrStr
|
||||
if (global.CompareArr(global.SERVER.addrArr, Node.addrArr) === 0) {
|
||||
Node.Self = 1
|
||||
Node.Self = true
|
||||
return 0;
|
||||
}
|
||||
var Hash = global.shaarr2(Buf.addrArr, Buf.HashRND);
|
||||
|
@ -16,6 +16,7 @@ import { secp256k1, RBTree } from "./library"
|
||||
import "./crypto-library"
|
||||
import CConnect from './connect'
|
||||
import { STreeBuffer } from './base';
|
||||
import CNode, { TeraSocket } from './node';
|
||||
const HARD_PACKET_PERIOD = 20;
|
||||
global.BUF_TYPE = 1;
|
||||
global.STR_TYPE = 2;
|
||||
@ -409,7 +410,7 @@ export default class CTransport extends CConnect {
|
||||
GetHashFromData(Info) {
|
||||
return global.shaarr(Info.Method + Info.Length + "-" + (Info.NodeTime - 0));
|
||||
}
|
||||
OnGetFromTCP(Node, Socket, Buf) {
|
||||
OnGetFromTCP(Node: CNode, Socket: TeraSocket, Buf) {
|
||||
if (!Node)
|
||||
return;
|
||||
if (!Node.Socket)
|
||||
|
@ -14,7 +14,7 @@ import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as crypto from 'crypto';
|
||||
global.START_SERVER = 1;
|
||||
import { WsServer, SendToClient } from '../rpc/server'
|
||||
import { teraManager } from '../rpc/manager'
|
||||
global.DATA_PATH = global.GetNormalPathString(global.DATA_PATH);
|
||||
global.CODE_PATH = global.GetNormalPathString(global.CODE_PATH);
|
||||
console.log("DATA DIR: " + global.DATA_PATH);
|
||||
@ -392,7 +392,7 @@ function AllAlive() {
|
||||
for (var i = 0; i < global.ArrMiningWrk.length; i++) {
|
||||
global.ArrMiningWrk[i].send({ cmd: "Alive", DELTA_CURRENT_TIME: global.DELTA_CURRENT_TIME });
|
||||
}
|
||||
SendToClient({ cmd: "Alive", DELTA_CURRENT_TIME: global.DELTA_CURRENT_TIME })
|
||||
teraManager.SendToClient({ cmd: "Alive", DELTA_CURRENT_TIME: global.DELTA_CURRENT_TIME })
|
||||
};
|
||||
|
||||
function ClearArrMining() {
|
||||
@ -512,7 +512,7 @@ function RunStopPOWProcess(Mode) {
|
||||
};
|
||||
|
||||
function SetCalcPOW(Block, cmd) {
|
||||
SendToClient({
|
||||
teraManager.SendToClient({
|
||||
cmd: cmd,
|
||||
BlockNum: Block.BlockNum,
|
||||
Account: global.GENERATE_BLOCK_ACCOUNT,
|
||||
@ -670,7 +670,7 @@ function RunOnce() {
|
||||
require("../core/update");
|
||||
global.RunOnUpdate();
|
||||
StartAllProcess(1);
|
||||
WsServer.start(8080);
|
||||
teraManager.WsServer.start(8080);
|
||||
// require("./dogs");
|
||||
if (global.RESTART_PERIOD_SEC) {
|
||||
var Period = (global.random(600) + global.RESTART_PERIOD_SEC);
|
||||
|
@ -46,6 +46,9 @@ function FastCalcBlock(msg) {
|
||||
FastBlock.RunCount = 0;
|
||||
try {
|
||||
if (CreatePOWVersionX(FastBlock)) {
|
||||
if (Block.HashCount) {
|
||||
powClient.send({ cmd: "HASHRATE", CountNonce: Block.HashCount, Hash: Block.Hash });
|
||||
}
|
||||
powClient.send({
|
||||
cmd: "POW",
|
||||
BlockNum: FastBlock.BlockNum,
|
||||
@ -53,7 +56,7 @@ function FastCalcBlock(msg) {
|
||||
Hash: FastBlock.Hash,
|
||||
PowHash: FastBlock.PowHash,
|
||||
AddrHash: FastBlock.AddrHash,
|
||||
Num: FastBlock.Num
|
||||
Num: FastBlock.NodeNum
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
@ -70,52 +73,6 @@ PROCESS.on('message', function(msg) {
|
||||
PROCESS.exit(0);
|
||||
}
|
||||
})
|
||||
// PROCESS.on('message', function(msg) {
|
||||
// LastAlive = Date.now();
|
||||
// if (msg.cmd === "FastCalcBlock") {
|
||||
// var FastBlock = msg;
|
||||
// StartHashPump(FastBlock);
|
||||
// FastBlock.RunCount = 0;
|
||||
// try {
|
||||
// if (CreatePOWVersionX(FastBlock))
|
||||
// process.send({
|
||||
// cmd: "POW",
|
||||
// BlockNum: FastBlock.BlockNum,
|
||||
// SeqHash: FastBlock.SeqHash,
|
||||
// Hash: FastBlock.Hash,
|
||||
// PowHash: FastBlock.PowHash,
|
||||
// AddrHash: FastBlock.AddrHash,
|
||||
// Num: FastBlock.Num
|
||||
// });
|
||||
// } catch (e) {
|
||||
// global.ToError(e);
|
||||
// }
|
||||
// } else {
|
||||
// if (msg.cmd === "SetBlock") {
|
||||
// var StartNonce = 1000000 * (1 + msg.Num);
|
||||
// if (Block.HashCount) {
|
||||
// process.send({ cmd: "HASHRATE", CountNonce: Block.HashCount, Hash: Block.Hash });
|
||||
// }
|
||||
// Block.HashCount = 0;
|
||||
// Block = msg;
|
||||
// Block.Time = Date.now();
|
||||
// Block.LastNonce = StartNonce;
|
||||
// Block.Period = global.CONSENSUS_PERIOD_TIME * Block.Percent / 100;
|
||||
// if (Block.Period > 0 && Block.RunPeriod > 0) {
|
||||
// CalcPOWHash();
|
||||
// if (idInterval !== undefined) {
|
||||
// clearInterval(idInterval);
|
||||
// }
|
||||
// idInterval = setInterval(CalcPOWHash, Block.RunPeriod);
|
||||
// }
|
||||
// } else
|
||||
// if (msg.cmd === "Alive") {
|
||||
// } else
|
||||
// if (msg.cmd === "Exit") {
|
||||
// PROCESS.exit(0);
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
|
||||
function CheckAlive() {
|
||||
if (global.NOALIVE)
|
||||
@ -127,32 +84,6 @@ function CheckAlive() {
|
||||
}
|
||||
};
|
||||
|
||||
// function CalcPOWHash() {
|
||||
// if (!Block.SeqHash)
|
||||
// return;
|
||||
// if ((new Date() as any) - Block.Time > Block.Period) {
|
||||
// clearInterval(idInterval);
|
||||
// idInterval = undefined;
|
||||
// return;
|
||||
// }
|
||||
// try {
|
||||
// if (CreatePOWVersionX(Block)) {
|
||||
// let msg = {
|
||||
// cmd: "POW",
|
||||
// BlockNum: Block.BlockNum,
|
||||
// SeqHash: Block.SeqHash,
|
||||
// Hash: Block.Hash,
|
||||
// PowHash: Block.PowHash,
|
||||
// AddrHash: Block.AddrHash,
|
||||
// Num: Block.Num
|
||||
// }
|
||||
// powClient.send(msg)
|
||||
// //process.send(msg);
|
||||
// }
|
||||
// } catch (e) {
|
||||
// global.ToError(e);
|
||||
// }
|
||||
// };
|
||||
global.BlockPump = undefined;
|
||||
var idIntervalPump = undefined;
|
||||
|
||||
@ -167,7 +98,7 @@ function StartHashPump(SetBlock) {
|
||||
MinerID: SetBlock.MinerID,
|
||||
Percent: SetBlock.Percent,
|
||||
LastNonce: 0,
|
||||
Num: SetBlock.Num,
|
||||
NodeNum: SetBlock.NodeNum,
|
||||
};
|
||||
}
|
||||
if (!idIntervalPump) {
|
||||
@ -188,12 +119,8 @@ function PumpHash() {
|
||||
EndTime = CurTime;
|
||||
return;
|
||||
}
|
||||
if (global.BlockPump.RunCount) {
|
||||
setTimeout(() => {
|
||||
powClient.send({ cmd: "HASHRATE", CountNonce: global.BlockPump.RunCount });
|
||||
}, 1)
|
||||
}
|
||||
global.BlockPump.LastNonce = global.BlockPump.LastNonce + global.BlockPump.Num * 100000
|
||||
global.BlockPump.LastNonce0 = global.BlockPump.LastNonce0 + global.BlockPump.Num * 100000
|
||||
CreatePOWVersionX(global.BlockPump, 1);
|
||||
} else {
|
||||
var Delta = CurTime - EndTime;
|
||||
|
@ -1,20 +1,24 @@
|
||||
import * as io from 'socket.io-client'
|
||||
|
||||
let host = process.env.TERA_HOST || 'http://127.0.0.1:8080/main'
|
||||
let host = process.env.TERA_HOST || 'http://127.0.0.1:8080/pow'
|
||||
|
||||
let powClient = io(host, {
|
||||
path: '/ws'
|
||||
})
|
||||
|
||||
powClient.on('connect', () => {
|
||||
// console.log(`Client ${powClient.id} connect ...`)
|
||||
powClient.emit('powclient', {})
|
||||
powClient.emit('web', `Connect to ${host} Successful...`)
|
||||
console.log(`Client ${powClient.id} connect ...`)
|
||||
SendToWebClient(`${global.PROCESS_NAME} Connect to ${host} Successful...`)
|
||||
powClient.send({ cmd: "online", message: "OK" })
|
||||
});
|
||||
|
||||
powClient.on('disconnect', (error) => {
|
||||
console.log(`Client disconnect Error: ${error}...`)
|
||||
process.exit(0)
|
||||
});
|
||||
|
||||
export { powClient }
|
||||
function SendToWebClient(msg: any) {
|
||||
powClient.emit('web', msg)
|
||||
}
|
||||
|
||||
export { powClient, SendToWebClient }
|
||||
|
36
src/rpc/manager.ts
Normal file
36
src/rpc/manager.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { CcServerBoot } from "@cc-server/core";
|
||||
import { TYPE, interfaces, io } from "@cc-server/ws";
|
||||
import { lazyInjectNamed, Container } from "@cc-server/ioc";
|
||||
import { PowNamespace, WebNamespace } from "./server";
|
||||
|
||||
class TeraManager {
|
||||
@lazyInjectNamed(TYPE.Namespace, PowNamespace.name)
|
||||
powNsp: interfaces.Namespace;
|
||||
@lazyInjectNamed(TYPE.Namespace, WebNamespace.name)
|
||||
webNsp: interfaces.Namespace;
|
||||
pows: { [key: string]: io.Socket };
|
||||
WsServer: CcServerBoot;
|
||||
constructor() {
|
||||
this.pows = {};
|
||||
let container = new Container();
|
||||
this.WsServer = new CcServerBoot(container).build();
|
||||
}
|
||||
SendToClient(msg: any) {
|
||||
this.webNsp.nsp.to('pow').send(JSON.stringify(msg))
|
||||
let index = 0;
|
||||
for (let id in this.pows) {
|
||||
const pow = this.pows[id];
|
||||
if (typeof msg === "object") {
|
||||
msg.NodeNum = index;
|
||||
}
|
||||
pow.send(msg)
|
||||
index++
|
||||
}
|
||||
}
|
||||
SendToWebClient(msg: any) {
|
||||
this.webNsp.nsp.send(msg)
|
||||
}
|
||||
}
|
||||
let teraManager = new TeraManager();
|
||||
|
||||
export { teraManager }
|
@ -1,94 +0,0 @@
|
||||
import { CcServerBoot } from '@cc-server/core'
|
||||
import { namespace, listener, io, TYPE, interfaces } from '@cc-server/ws'
|
||||
import { Namespace } from 'socket.io';
|
||||
import { Container } from 'inversify';
|
||||
|
||||
let pows: io.Socket[] = [];
|
||||
|
||||
@namespace('/main')
|
||||
class TeraNamespace implements interfaces.Namespace {
|
||||
nsp: Namespace;
|
||||
@listener()
|
||||
webclient(socket: io.Socket) {
|
||||
socket.join('web');
|
||||
global.ToLog(`${socket.id} WebClient Connected...`)
|
||||
}
|
||||
@listener()
|
||||
web(socket: io.Socket, msg: any) {
|
||||
socket.to('web').send('Recover From Pow: ' + JSON.stringify(msg))
|
||||
}
|
||||
@listener()
|
||||
webmsg(socket: io.Socket, msg: any) {
|
||||
global.ToLog(`Recover webmsg ${JSON.stringify(msg)}`)
|
||||
switch (msg.cmd) {
|
||||
case "list":
|
||||
socket.send(`Client List:`)
|
||||
let index = 0;
|
||||
for (let id in pows) {
|
||||
const pow = pows[id];
|
||||
socket.send(`${index} => ${pow.id}: ${pow.conn.remoteAddress}`)
|
||||
index++
|
||||
}
|
||||
break;
|
||||
case "pow":
|
||||
socket.send('Join Pow Room...')
|
||||
socket.join('pow')
|
||||
break;
|
||||
case "leavepow":
|
||||
socket.leave('pow')
|
||||
socket.send('Leave Pow Room...')
|
||||
break;
|
||||
}
|
||||
}
|
||||
@listener()
|
||||
powclient(socket: io.Socket) {
|
||||
pows[socket.id] = socket;
|
||||
// global.ToLog(`${socket.id} PowClient Connected...`)
|
||||
}
|
||||
@listener()
|
||||
message(socket: io.Socket, msg: any) {
|
||||
socket.to('pow').send(`${JSON.stringify(msg)}`)
|
||||
switch (msg.cmd) {
|
||||
case "POW":
|
||||
global.SERVER.MiningProcess(msg);
|
||||
break;
|
||||
case "HASHRATE":
|
||||
global.ADD_HASH_RATE(msg.CountNonce);
|
||||
break;
|
||||
}
|
||||
}
|
||||
disconnect(socket: io.Socket) {
|
||||
// socket.to('web').send(`Client ${socket.id} ${socket.conn.remoteAddress} disconnect...`)
|
||||
delete pows[socket.id]
|
||||
}
|
||||
}
|
||||
|
||||
let container = new Container();
|
||||
let WsServer = new CcServerBoot(container).build();
|
||||
|
||||
function getServer(): TeraNamespace {
|
||||
return container.getNamed<TeraNamespace>(TYPE.Namespace, TeraNamespace.name);
|
||||
}
|
||||
|
||||
function getNamespace(): Namespace {
|
||||
return getServer().nsp;
|
||||
}
|
||||
|
||||
function SendToClient(msg: any) {
|
||||
getNamespace().to('pow').send(JSON.stringify(msg))
|
||||
let index = 0;
|
||||
for (let id in pows) {
|
||||
const pow = pows[id];
|
||||
if (typeof msg === "object") {
|
||||
msg.Num = index;
|
||||
}
|
||||
pow.send(msg)
|
||||
index++
|
||||
}
|
||||
}
|
||||
|
||||
function SendToWebClient(msg: any) {
|
||||
getNamespace().to('web').send(msg)
|
||||
}
|
||||
|
||||
export { WsServer, SendToClient, SendToWebClient }
|
2
src/rpc/server/index.ts
Normal file
2
src/rpc/server/index.ts
Normal file
@ -0,0 +1,2 @@
|
||||
export * from './ws-server'
|
||||
export * from './web-server'
|
22
src/rpc/server/web-server.ts
Normal file
22
src/rpc/server/web-server.ts
Normal file
@ -0,0 +1,22 @@
|
||||
import { controller, httpGet } from '@cc-server/binding';
|
||||
import { teraManager } from '../manager';
|
||||
|
||||
@controller('')
|
||||
class TeraController {
|
||||
@httpGet('/clients')
|
||||
clients() {
|
||||
let list = [];
|
||||
let index = 0;
|
||||
for (let id in teraManager.pows) {
|
||||
const pow = teraManager.pows[id];
|
||||
list.push({
|
||||
id: pow.id,
|
||||
index,
|
||||
address: pow.conn.remoteAddress
|
||||
})
|
||||
index++
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
export default TeraController;
|
6
src/rpc/server/ws-server/index.ts
Normal file
6
src/rpc/server/ws-server/index.ts
Normal file
@ -0,0 +1,6 @@
|
||||
import WebNamespace from './web-server'
|
||||
import PowNamespace from './pow-server'
|
||||
export {
|
||||
WebNamespace,
|
||||
PowNamespace
|
||||
}
|
36
src/rpc/server/ws-server/pow-server.ts
Normal file
36
src/rpc/server/ws-server/pow-server.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { namespace, listener, io, TYPE, interfaces } from '@cc-server/ws'
|
||||
import { Namespace } from 'socket.io';
|
||||
import { lazyInjectNamed } from '@cc-server/ioc';
|
||||
import { teraManager } from '../../manager';
|
||||
import WebNamespace from './web-server'
|
||||
|
||||
@namespace('/pow')
|
||||
class PowNamespace implements interfaces.Namespace {
|
||||
@lazyInjectNamed(TYPE.Namespace, WebNamespace.name)
|
||||
webNsp: interfaces.Namespace;
|
||||
nsp: Namespace;
|
||||
connection(socket: io.Socket) {
|
||||
teraManager.pows[socket.id] = socket;
|
||||
}
|
||||
@listener()
|
||||
web(socket: io.Socket, msg: any) {
|
||||
this.webNsp.nsp.send('Recover From Pow: ' + JSON.stringify(msg))
|
||||
}
|
||||
@listener()
|
||||
message(socket: io.Socket, msg: any) {
|
||||
this.webNsp.nsp.to('pow').send(msg);
|
||||
switch (msg.cmd) {
|
||||
case "POW":
|
||||
global.SERVER.MiningProcess(msg);
|
||||
break;
|
||||
case "HASHRATE":
|
||||
global.ADD_HASH_RATE(msg.CountNonce);
|
||||
break;
|
||||
}
|
||||
}
|
||||
disconnect(socket: io.Socket) {
|
||||
delete teraManager.pows[socket.id]
|
||||
}
|
||||
}
|
||||
|
||||
export default PowNamespace;
|
38
src/rpc/server/ws-server/web-server.ts
Normal file
38
src/rpc/server/ws-server/web-server.ts
Normal file
@ -0,0 +1,38 @@
|
||||
import { namespace, listener, io, TYPE, interfaces } from '@cc-server/ws'
|
||||
import { Namespace } from 'socket.io';
|
||||
import { lazyInjectNamed } from '@cc-server/ioc';
|
||||
import { teraManager } from '../../manager';
|
||||
|
||||
@namespace('/web')
|
||||
class WebNamespace implements interfaces.Namespace {
|
||||
nsp: Namespace;
|
||||
|
||||
connection(socket: io.Socket) {
|
||||
socket.send('Connect succseful...')
|
||||
}
|
||||
@listener()
|
||||
webmsg(socket: io.Socket, msg: any) {
|
||||
global.ToLog(`Recover webmsg ${JSON.stringify(msg)}`)
|
||||
switch (msg.cmd) {
|
||||
case "list":
|
||||
socket.send(`Client List:`)
|
||||
let index = 0;
|
||||
for (let id in teraManager.pows) {
|
||||
const pow = teraManager.pows[id];
|
||||
socket.send(`${index} => ${pow.id}: ${pow.conn.remoteAddress}`)
|
||||
index++
|
||||
}
|
||||
break;
|
||||
case "pow":
|
||||
socket.send('Join Pow Room...')
|
||||
socket.join('pow')
|
||||
break;
|
||||
case "leavepow":
|
||||
socket.leave('pow')
|
||||
socket.send('Leave Pow Room...')
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default WebNamespace;
|
@ -30,7 +30,13 @@ function Fork(Path, ArrArgs?): TeraChildProcess {
|
||||
let ArrMiningWrk = []
|
||||
|
||||
function RunProcess() {
|
||||
console.log(`Start add ${thread} pow process`)
|
||||
for (var R = 0; R < thread; R++) {
|
||||
AddPowProcess()
|
||||
}
|
||||
}
|
||||
|
||||
function AddPowProcess() {
|
||||
let Worker = Fork('./process/pow-process');
|
||||
ArrMiningWrk.push(Worker);
|
||||
Worker.Num = ArrMiningWrk.length;
|
||||
@ -47,22 +53,30 @@ function RunProcess() {
|
||||
console.log('ERROR IN PROCESS: ' + err);
|
||||
});
|
||||
Worker.on('close', function(code) {
|
||||
console.log(`STOP PROCESS: ${Worker.Num} pid: ${Worker.pid} code: ${code}`)
|
||||
for (var i = 0; i < ArrMiningWrk.length; i++) {
|
||||
if (ArrMiningWrk[i].pid === Worker.pid) {
|
||||
console.log("Delete wrk from arr - pid:" + Worker.pid);
|
||||
console.log(`STOP PROCESS: ${Worker.Num} pid: ${Worker.pid} code: ${code} delete wrk`);
|
||||
ArrMiningWrk.splice(i, 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
console.log("START MINER PROCESS COUNT: " + thread + " Memory: " + ProcessMemorySize / 1024 / 1024 + " Mb for each process");
|
||||
|
||||
setInterval(() => {
|
||||
async function CheckAlive() {
|
||||
if (!ArrMiningWrk.length) {
|
||||
console.log(`ArrMiningWrk.length == ${ArrMiningWrk.length} Starting all node...`)
|
||||
RunProcess();
|
||||
}
|
||||
}, 1000)
|
||||
if (ArrMiningWrk.length < thread) {
|
||||
AddPowProcess()
|
||||
}
|
||||
setTimeout(CheckAlive, 1000)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await CheckAlive()
|
||||
}
|
||||
|
||||
main()
|
Loading…
Reference in New Issue
Block a user