1
0
forked from circlecloud/tera

refactor: rewrite rpc server client

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
MiaoWoo 2019-07-20 13:12:21 +08:00
parent fd1b23a4c3
commit b05a00f87d
18 changed files with 315 additions and 298 deletions

View File

@ -23,6 +23,7 @@
"start": "node dist/run-node.js" "start": "node dist/run-node.js"
}, },
"dependencies": { "dependencies": {
"@cc-server/binding": "^0.6.1",
"@cc-server/core": "^0.6.1", "@cc-server/core": "^0.6.1",
"@cc-server/ws": "^0.6.1", "@cc-server/ws": "^0.6.1",
"bintrees": "^1.0.2", "bintrees": "^1.0.2",

View File

@ -22,71 +22,7 @@
<body> <body>
<div id="terminal" style="height: 100%;"></div> <div id="terminal" style="height: 100%;"></div>
<script type="text/javascript"> <script src="index.js"></script>
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>
</body> </body>
</html> </html>

69
public/index.js Normal file
View 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();
};

View File

@ -12,7 +12,7 @@
import CBlock from './block-loader' import CBlock from './block-loader'
import { RBTree } from './library' import { RBTree } from './library'
import { STreeBuffer } from './base'; import { STreeBuffer } from './base';
import { SendToWebClient } from '../rpc/server' import { teraManager } from '../rpc/manager'
require('./library'); require('./library');
require('./crypto-library'); require('./crypto-library');
const TX_PROCESS_TIME = 100; const TX_PROCESS_TIME = 100;
@ -1352,16 +1352,16 @@ export default class CConsensus extends CBlock {
MiningProcess(msg) { MiningProcess(msg) {
var BlockMining = this.GetBlock(msg.BlockNum); var BlockMining = this.GetBlock(msg.BlockNum);
if (!BlockMining) { if (!BlockMining) {
SendToWebClient({ teraManager.SendToWebClient({
msg: msg, msg: msg,
errror: '!BlockMining' error: '!BlockMining'
}) })
return; return;
} }
if (!BlockMining.StartMining || BlockMining.bSave) { if (!BlockMining.StartMining || BlockMining.bSave) {
SendToWebClient({ teraManager.SendToWebClient({
msg: msg, msg: msg,
errror: `!BlockMining.StartMining ${BlockMining.StartMining} || BlockMining.bSave ${BlockMining.bSave}` error: `!BlockMining.StartMining ${BlockMining.StartMining} || BlockMining.bSave ${BlockMining.bSave}`
}) })
return; return;
} }
@ -1404,19 +1404,19 @@ export default class CConsensus extends CBlock {
setTimeout(() => { setTimeout(() => {
let webmsg: any = { BlockNum: msg.BlockNum } let webmsg: any = { BlockNum: msg.BlockNum }
webmsg.Mining = { 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), Hash: global.GetHexFromArr(BlockMining.Hash),
SeqHash: global.GetHexFromArr(BlockMining.Hash) PowHash: global.GetHexFromArr(BlockMining.PowHash)
}
webmsg.New = {
Hash: global.GetHexFromArr(ValueNew.Hash),
PowHash: global.GetHexFromArr(ValueNew.PowHash)
} }
Object.assign(webmsg, { Object.assign(webmsg, {
HashCount, HashCount,
Power, Power,
Num: msg.Num Num: msg.NodeNum
}) })
SendToWebClient(webmsg) teraManager.SendToWebClient(webmsg)
}, 1) }, 1)
} }
} }

View File

@ -1193,10 +1193,19 @@ global.HTTPCaller.GetHistoryTransactions = function(Params) {
function GetCopyBlock(Block) { function GetCopyBlock(Block) {
var Result: any = { var Result: any = {
BlockNum: Block.BlockNum, bSave: Block.bSave, TreeHash: global.GetHexFromAddres(Block.TreeHash), AddrHash: global.GetHexFromAddres(Block.AddrHash), BlockNum: Block.BlockNum,
PrevHash: global.GetHexFromAddres(Block.PrevHash), SumHash: global.GetHexFromAddres(Block.SumHash), SumPow: Block.SumPow, TrDataPos: Block.TrDataPos, bSave: Block.bSave,
TrDataLen: Block.TrDataLen, SeqHash: global.GetHexFromAddres(Block.SeqHash), Hash: global.GetHexFromAddres(Block.Hash), Power: global.GetPowPower(Block.PowHash), TreeHash: global.GetHexFromAddres(Block.TreeHash),
TrCount: Block.TrCount, arrContent: Block.arrContent, 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; return Result;
}; };

View File

@ -13,6 +13,16 @@ import "./library"
import * as net from "net" import * as net from "net"
import { secp256k1, RBTree } from '../core/library' import { secp256k1, RBTree } from '../core/library'
var ConnectIDCount = 1; 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 { export default class CNode {
addrStr addrStr
ip ip
@ -72,7 +82,7 @@ export default class CNode {
CanHardTraffic CanHardTraffic
BufWriteLength BufWriteLength
BufWrite BufWrite
SendPacket SendPacket: RBTree<any>
ConnectCount ConnectCount
TrafficArr TrafficArr
SendTrafficCurrent SendTrafficCurrent
@ -80,11 +90,11 @@ export default class CNode {
ErrCount ErrCount
ErrCountAll ErrCountAll
SendPacketNum SendPacketNum
Socket Socket: TeraSocket
Socket2 Socket2: TeraSocket
ReconnectFromServer ReconnectFromServer
SecretForReconnect SecretForReconnect
Self Self: boolean
addrStrTemp addrStrTemp
DoubleConnection DoubleConnection
PubKey PubKey
@ -191,7 +201,7 @@ export default class CNode {
NODE.Socket.ConnectToServer = true NODE.Socket.ConnectToServer = true
SetSocketStatus(NODE.Socket, 2) SetSocketStatus(NODE.Socket, 2)
} }
}) }) as TeraSocket
SetSocketStatus(NODE.Socket, 1) SetSocketStatus(NODE.Socket, 1)
NODE.Socket.Node = NODE NODE.Socket.Node = NODE
NODE.Socket.ConnectID = "~C" + ConnectIDCount NODE.Socket.ConnectID = "~C" + ConnectIDCount
@ -210,7 +220,7 @@ export default class CNode {
NODE.Socket2.ConnectToServer = true NODE.Socket2.ConnectToServer = true
SetSocketStatus(NODE.Socket2, 2) SetSocketStatus(NODE.Socket2, 2)
} }
}) }) as TeraSocket
SetSocketStatus(NODE.Socket2, 1) SetSocketStatus(NODE.Socket2, 1)
NODE.Socket2.Node = NODE NODE.Socket2.Node = NODE
NODE.Socket2.ConnectID = "~R" + ConnectIDCount NODE.Socket2.ConnectID = "~R" + ConnectIDCount
@ -286,7 +296,7 @@ export default class CNode {
} }
else else
if (Str === "SELF") { if (Str === "SELF") {
NODE.Self = 1 NODE.Self = true
} }
else else
if (Str === "DOUBLE") { if (Str === "DOUBLE") {
@ -395,7 +405,7 @@ export default class CNode {
Node.addrArr = Buf.addrArr Node.addrArr = Buf.addrArr
Node.addrStr = addrStr Node.addrStr = addrStr
if (global.CompareArr(global.SERVER.addrArr, Node.addrArr) === 0) { if (global.CompareArr(global.SERVER.addrArr, Node.addrArr) === 0) {
Node.Self = 1 Node.Self = true
return 0; return 0;
} }
var Hash = global.shaarr2(Buf.addrArr, Buf.HashRND); var Hash = global.shaarr2(Buf.addrArr, Buf.HashRND);

View File

@ -16,6 +16,7 @@ import { secp256k1, RBTree } from "./library"
import "./crypto-library" import "./crypto-library"
import CConnect from './connect' import CConnect from './connect'
import { STreeBuffer } from './base'; import { STreeBuffer } from './base';
import CNode, { TeraSocket } from './node';
const HARD_PACKET_PERIOD = 20; const HARD_PACKET_PERIOD = 20;
global.BUF_TYPE = 1; global.BUF_TYPE = 1;
global.STR_TYPE = 2; global.STR_TYPE = 2;
@ -409,7 +410,7 @@ export default class CTransport extends CConnect {
GetHashFromData(Info) { GetHashFromData(Info) {
return global.shaarr(Info.Method + Info.Length + "-" + (Info.NodeTime - 0)); return global.shaarr(Info.Method + Info.Length + "-" + (Info.NodeTime - 0));
} }
OnGetFromTCP(Node, Socket, Buf) { OnGetFromTCP(Node: CNode, Socket: TeraSocket, Buf) {
if (!Node) if (!Node)
return; return;
if (!Node.Socket) if (!Node.Socket)

View File

@ -14,7 +14,7 @@ import * as fs from 'fs'
import * as os from 'os' import * as os from 'os'
import * as crypto from 'crypto'; import * as crypto from 'crypto';
global.START_SERVER = 1; global.START_SERVER = 1;
import { WsServer, SendToClient } from '../rpc/server' import { teraManager } from '../rpc/manager'
global.DATA_PATH = global.GetNormalPathString(global.DATA_PATH); global.DATA_PATH = global.GetNormalPathString(global.DATA_PATH);
global.CODE_PATH = global.GetNormalPathString(global.CODE_PATH); global.CODE_PATH = global.GetNormalPathString(global.CODE_PATH);
console.log("DATA DIR: " + global.DATA_PATH); console.log("DATA DIR: " + global.DATA_PATH);
@ -392,7 +392,7 @@ function AllAlive() {
for (var i = 0; i < global.ArrMiningWrk.length; i++) { for (var i = 0; i < global.ArrMiningWrk.length; i++) {
global.ArrMiningWrk[i].send({ cmd: "Alive", DELTA_CURRENT_TIME: global.DELTA_CURRENT_TIME }); 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() { function ClearArrMining() {
@ -512,7 +512,7 @@ function RunStopPOWProcess(Mode) {
}; };
function SetCalcPOW(Block, cmd) { function SetCalcPOW(Block, cmd) {
SendToClient({ teraManager.SendToClient({
cmd: cmd, cmd: cmd,
BlockNum: Block.BlockNum, BlockNum: Block.BlockNum,
Account: global.GENERATE_BLOCK_ACCOUNT, Account: global.GENERATE_BLOCK_ACCOUNT,
@ -670,7 +670,7 @@ function RunOnce() {
require("../core/update"); require("../core/update");
global.RunOnUpdate(); global.RunOnUpdate();
StartAllProcess(1); StartAllProcess(1);
WsServer.start(8080); teraManager.WsServer.start(8080);
// require("./dogs"); // require("./dogs");
if (global.RESTART_PERIOD_SEC) { if (global.RESTART_PERIOD_SEC) {
var Period = (global.random(600) + global.RESTART_PERIOD_SEC); var Period = (global.random(600) + global.RESTART_PERIOD_SEC);

View File

@ -46,6 +46,9 @@ function FastCalcBlock(msg) {
FastBlock.RunCount = 0; FastBlock.RunCount = 0;
try { try {
if (CreatePOWVersionX(FastBlock)) { if (CreatePOWVersionX(FastBlock)) {
if (Block.HashCount) {
powClient.send({ cmd: "HASHRATE", CountNonce: Block.HashCount, Hash: Block.Hash });
}
powClient.send({ powClient.send({
cmd: "POW", cmd: "POW",
BlockNum: FastBlock.BlockNum, BlockNum: FastBlock.BlockNum,
@ -53,7 +56,7 @@ function FastCalcBlock(msg) {
Hash: FastBlock.Hash, Hash: FastBlock.Hash,
PowHash: FastBlock.PowHash, PowHash: FastBlock.PowHash,
AddrHash: FastBlock.AddrHash, AddrHash: FastBlock.AddrHash,
Num: FastBlock.Num Num: FastBlock.NodeNum
}); });
} }
} catch (e) { } catch (e) {
@ -70,52 +73,6 @@ PROCESS.on('message', function(msg) {
PROCESS.exit(0); 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() { function CheckAlive() {
if (global.NOALIVE) 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; global.BlockPump = undefined;
var idIntervalPump = undefined; var idIntervalPump = undefined;
@ -167,7 +98,7 @@ function StartHashPump(SetBlock) {
MinerID: SetBlock.MinerID, MinerID: SetBlock.MinerID,
Percent: SetBlock.Percent, Percent: SetBlock.Percent,
LastNonce: 0, LastNonce: 0,
Num: SetBlock.Num, NodeNum: SetBlock.NodeNum,
}; };
} }
if (!idIntervalPump) { if (!idIntervalPump) {
@ -188,12 +119,8 @@ function PumpHash() {
EndTime = CurTime; EndTime = CurTime;
return; 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.LastNonce = global.BlockPump.LastNonce + global.BlockPump.Num * 100000
global.BlockPump.LastNonce0 = global.BlockPump.LastNonce0 + global.BlockPump.Num * 100000
CreatePOWVersionX(global.BlockPump, 1); CreatePOWVersionX(global.BlockPump, 1);
} else { } else {
var Delta = CurTime - EndTime; var Delta = CurTime - EndTime;

View File

@ -1,20 +1,24 @@
import * as io from 'socket.io-client' 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, { let powClient = io(host, {
path: '/ws' path: '/ws'
}) })
powClient.on('connect', () => { powClient.on('connect', () => {
// console.log(`Client ${powClient.id} connect ...`) console.log(`Client ${powClient.id} connect ...`)
powClient.emit('powclient', {}) SendToWebClient(`${global.PROCESS_NAME} Connect to ${host} Successful...`)
powClient.emit('web', `Connect to ${host} Successful...`)
powClient.send({ cmd: "online", message: "OK" }) powClient.send({ cmd: "online", message: "OK" })
}); });
powClient.on('disconnect', (error) => { powClient.on('disconnect', (error) => {
console.log(`Client disconnect Error: ${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
View 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 }

View File

@ -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
View File

@ -0,0 +1,2 @@
export * from './ws-server'
export * from './web-server'

View 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;

View File

@ -0,0 +1,6 @@
import WebNamespace from './web-server'
import PowNamespace from './pow-server'
export {
WebNamespace,
PowNamespace
}

View 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;

View 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;

View File

@ -30,7 +30,13 @@ function Fork(Path, ArrArgs?): TeraChildProcess {
let ArrMiningWrk = [] let ArrMiningWrk = []
function RunProcess() { function RunProcess() {
console.log(`Start add ${thread} pow process`)
for (var R = 0; R < thread; R++) { for (var R = 0; R < thread; R++) {
AddPowProcess()
}
}
function AddPowProcess() {
let Worker = Fork('./process/pow-process'); let Worker = Fork('./process/pow-process');
ArrMiningWrk.push(Worker); ArrMiningWrk.push(Worker);
Worker.Num = ArrMiningWrk.length; Worker.Num = ArrMiningWrk.length;
@ -47,22 +53,30 @@ function RunProcess() {
console.log('ERROR IN PROCESS: ' + err); console.log('ERROR IN PROCESS: ' + err);
}); });
Worker.on('close', function(code) { Worker.on('close', function(code) {
console.log(`STOP PROCESS: ${Worker.Num} pid: ${Worker.pid} code: ${code}`)
for (var i = 0; i < ArrMiningWrk.length; i++) { for (var i = 0; i < ArrMiningWrk.length; i++) {
if (ArrMiningWrk[i].pid === Worker.pid) { 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); ArrMiningWrk.splice(i, 1);
} }
} }
}); });
} }
}
console.log("START MINER PROCESS COUNT: " + thread + " Memory: " + ProcessMemorySize / 1024 / 1024 + " Mb for each process"); console.log("START MINER PROCESS COUNT: " + thread + " Memory: " + ProcessMemorySize / 1024 / 1024 + " Mb for each process");
setInterval(() => { async function CheckAlive() {
if (!ArrMiningWrk.length) { if (!ArrMiningWrk.length) {
console.log(`ArrMiningWrk.length == ${ArrMiningWrk.length} Starting all node...`) console.log(`ArrMiningWrk.length == ${ArrMiningWrk.length} Starting all node...`)
RunProcess(); RunProcess();
} }
}, 1000) if (ArrMiningWrk.length < thread) {
AddPowProcess()
}
setTimeout(CheckAlive, 1000)
}
async function main() {
await CheckAlive()
}
main()