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

CoffeeScript bidirectional client


May 09, 2021 CoffeeScript


Table of contents


Two-way client

Problem

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

Solution

Create a two-way TCP client.

In node .js

net = require 'net'

domain = 'localhost'
port = 9001

ping = (socket, delay) ->
    console.log "Pinging server"
    socket.write "Ping"
    nextPing = -> ping(socket, delay)
    setTimeout nextPing, delay

connection = net.createConnection port, domain

connection.on 'connect', () ->
    console.log "Opened connection to #{domain}:#{port}"
    ping connection, 2000

connection.on 'data', (data) ->
    console.log "Received: #{data}"

connection.on 'end', (data) ->
    console.log "Connection closed"
    process.exit()

Use the example

Access to Bi-Directional Server:

$ coffee bi-directional-client.coffee
Opened connection to localhost:9001
Pinging server
Received: You have 0 peers on this server
Pinging server
Received: You have 0 peers on this server
Pinging server
Received: You have 1 peer on this server
[...]
Connection closed

Discuss

This particular example initiates contact with the server and @connection in the .on 'connect' handler. A lot of work is done in a real user, @connection.on 'data' to process the output from the server. @ping@ function recursion is intended to show that continuous communication with the server may be removed by the real user.

See also Bi-Directional Server, Basic Client, and Basic Server.

Practice

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