Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript bidirectional server


May 09, 2021 CoffeeScript


Table of contents


Two-way server

Problem

You want to provide continuous service through the network and maintain continuous contact with customers.

Solution

Create a two-way TCP server.

In node .js

net = require 'net'

domain = 'localhost'
port = 9001

server = net.createServer (socket) ->
    console.log "New connection from #{socket.remoteAddress}"

    socket.on 'data', (data) ->
        console.log "#{socket.remoteAddress} sent: #{data}"
        others = server.connections - 1
        socket.write "You have #{others} #{others == 1 and "peer" or "peers"} on this server"

console.log "Listening to #{domain}:#{port}"
server.listen port, domain

Use the example

Access to Bi-Directional Client:

$ coffee bi-directional-server.coffee
Listening to localhost:9001
New connection from 127.0.0.1
127.0.0.1 sent: Ping
127.0.0.1 sent: Ping
127.0.0.1 sent: Ping
[...]

Discuss

Most of the work @socket all the inputs in the server.on 'data'. A real server might pass the data to another function to process and generate any response for the source program to process.

Practice

  • Add support for selected target domains and ports based on command line parameters or profiles.