-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.js
103 lines (85 loc) · 2.74 KB
/
socket.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
const net = require('net');
const { exec } = require('child_process');
class Command {
constructor() {
this.commands = {
"terminal\n": this.commandTerminal,
"google\n": this.commandGoogle,
"youtube\n": this.commandYoutube,
"calculator\n": this.commandCalculator,
"suspend\n": this.commandSuspend
};
}
commandTerminal() {
exec('gnome-terminal');
}
commandGoogle() {
exec('google-chrome');
}
commandYoutube() {
exec('google-chrome https://www.youtube.com');
}
commandCalculator() {
exec('gnome-calculator');
}
commandSuspend() {
exec('sudo pm-suspend');
}
}
class Server extends Command {
constructor(ipAddress, portNumber) {
super();
this.ipAddress = ipAddress;
this.portNumber = portNumber;
this.pendingNum = 1;
this.dataBuffer = "";
this.str = Buffer.alloc(100);
this.serverListeningSocket = null;
this.serverConnectionSocket = null;
}
serverInit() {
/*Creating the server socket*/
this.serverListeningSocket = net.createServer();
this.serverListeningSocket.listen(this.portNumber, this.ipAddress, () => {
console.log(`Server listening on ${this.ipAddress}:${this.portNumber}`);
});
this.serverListeningSocket.on('connection', (socket) => {
console.log('Client connected');
this.serverConnectionSocket = socket;
this.serverConnectionSocket.on('data', (data) => {
this.dataBuffer = data.toString();
console.log("Message from client:", this.dataBuffer);
this.dataBuffer = this.dataBuffer.toLowerCase();
this.serverExecuteCommand();
});
this.serverConnectionSocket.on('close', () => {
console.log('Client disconnected');
this.serverClose();
});
this.serverConnectionSocket.on('error', (err) => {
console.error('Socket error:', err);
this.serverClose();
});
});
}
serverSend(message) {
this.serverConnectionSocket.write(message);
}
serverExecuteCommand() {
const command = this.commands[this.dataBuffer];
if (command) {
command.call(this);
} else {
console.error('Invalid command received from client');
}
}
serverClose() {
if (this.serverListeningSocket) {
this.serverListeningSocket.close(() => {
console.log('Server closed');
});
}
}
}
const myServer = new Server("192.168.1.21", 8080);
myServer.serverInit();