Created
August 15, 2019 11:35
-
-
Save isaacgr/3eb2552591b57feccfc05d7ee6ab4f86 to your computer and use it in GitHub Desktop.
Client server using a protocol and a factory. Written in js, using the same principle as Pythons Twisted.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const net = require('net') | |
class ServerProtocol { | |
constructor(client){ | |
this.client = client | |
this.buffer = "" | |
this.factory = null | |
} | |
handleData(){ | |
this.client.on('data', (data) => { | |
this.buffer += data | |
console.log(this.buffer) | |
}) | |
this.client.on('end', () => { | |
this.factory.connectionClosed(this.client) | |
console.log('client disconnected') | |
}) | |
} | |
} | |
class ServerFactory { | |
constructor(){ | |
this.server = new net.Server() | |
this.connectedClients = [] | |
} | |
listen(){ | |
this.server.listen({port: 8100},() => { | |
console.log(`server listening on ${this.server.address().port}`) | |
}) | |
} | |
start(){ | |
this.server.on('connection', (client) => { | |
console.log('client connected') | |
this.connectedClients.push(client) | |
const serverProtocol = new ServerProtocol(client) | |
serverProtocol.factory = this | |
serverProtocol.handleData() | |
}) | |
} | |
connectionClosed(client){ | |
this.connectedClients.splice(this.connectedClients.indexOf(client)) // remove the client from the connected clients list | |
} | |
} | |
const serverFactory = new ServerFactory() | |
serverFactory.listen() | |
serverFactory.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment