summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGianni Ceccarelli <gianni.ceccarelli@broadbean.com>2019-07-30 09:46:15 +0100
committerGianni Ceccarelli <gianni.ceccarelli@broadbean.com>2019-07-30 09:47:01 +0100
commit64b098943c02cd1448576272da34c2a6f4b0bc1b (patch)
tree96d2910c6e8fb31b68b2f0038fddadc86b6fe654
parenthalf JS implementation (diff)
downloadmixed-server-64b098943c02cd1448576272da34c2a6f4b0bc1b.tar.gz
mixed-server-64b098943c02cd1448576272da34c2a6f4b0bc1b.tar.bz2
mixed-server-64b098943c02cd1448576272da34c2a6f4b0bc1b.zip
other half of JS implementation
-rw-r--r--js/mixed-server.js65
1 files changed, 65 insertions, 0 deletions
diff --git a/js/mixed-server.js b/js/mixed-server.js
index 3e103ed..966db7b 100644
--- a/js/mixed-server.js
+++ b/js/mixed-server.js
@@ -74,6 +74,67 @@ class HTTPController {
}
HTTPController.url_parse = require('url').parse;
+class LineController {
+ constructor(model,view) {
+ this.model = model;
+ this.view = view;
+ }
+
+ on_command(conn,command,args_string) {
+ if (command == 'get') {
+ this.get_words(conn,args_string);
+ }
+ else if (command == 'put') {
+ this.put_words(conn,args_string);
+ }
+ else {
+ this.reply(conn,"bad command, only 'get' and 'put'");
+ }
+ }
+
+ reply(conn,text) {
+ conn.write(`${text}\n`);
+ }
+
+ get_words(conn,args_string) {
+ const how_many = parseInt(args_string,10) || 10;
+ const most_common_pairs = this.model.get_most_common_pairs(how_many);
+ const table = this.view.table_from_ranked_pairs(most_common_pairs);
+
+ this.reply(conn,table);
+ }
+
+ put_words(conn,args_string) {
+ const words = this.view.words_from_input(args_string);
+ this.model.add_words(words);
+ this.reply(conn,'ok');
+ }
+}
+
+const net = require('net');
+class TextServer extends net.Server {
+ constructor(controller) {
+ super( {}, (c) => {
+ c.setEncoding('utf-8');
+ let input='';
+ c.on('data', (buffer) => {
+ input += buffer;
+ let lines = input.split(/\r?\n/);
+ input = lines.pop();
+ for (const line of lines) {
+ const m = line.match(/^(\S+)(?:\s+(.+))?$/);
+ if (m) {
+ controller.on_command(
+ c,
+ m[1], m[2],
+ );
+ }
+ }
+ });
+ });
+ }
+}
+
const model = new Model();
const view = new View();
@@ -84,3 +145,7 @@ const httpserver = http.createServer((req,res) => {
});
httpserver.listen(8080,'localhost');
+
+const linecontroller = new LineController(model,view);
+const textserver = new TextServer(linecontroller);
+textserver.listen(2020,'localhost');