Skip to content

Instantly share code, notes, and snippets.

@isaacgr
Created August 15, 2019 11:35
Show Gist options
  • Save isaacgr/3eb2552591b57feccfc05d7ee6ab4f86 to your computer and use it in GitHub Desktop.
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.
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