Created
July 2, 2012 10:30
-
-
Save andykent/3032537 to your computer and use it in GitHub Desktop.
A Small TCP Echo Server
This file contains 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
require "socket" | |
s = TCPSocket.new 'localhost', 1234 | |
s.puts "name: Andy" | |
s.puts "Hello World" |
This file contains 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
# requires node, coffee-script, node-terminal | |
# install nodejs then | |
# npm install coffee-script node-terminal | |
# run with `coffee echo.coffee` | |
PORT = 1234 | |
net = require 'net' | |
terminal = require 'node-terminal' | |
msg = (user, action, message) -> | |
terminal.color('magenta').write(user) | |
terminal.color('blue').write(" #{action}: ").reset() | |
terminal.write(message).reset().nl() | |
server = net.createServer (socket) -> | |
name = socket.remoteAddress | |
msg name, 'arrived', "Welcome #{name}!" | |
socket.on 'data', (d) -> | |
for line in d.toString().split("\n") when line.length > 0 | |
if match = line.match(/^name: (.+)/i) | |
oldName = name | |
name = match[1] | |
msg(oldName, 'changed names', "#{oldName} is now know as #{name}") | |
else if match = line.match(/^https?:\/\//i) | |
msg(name, 'opened', line) | |
require('child_process').spawn 'open', [line] | |
else if match = line.match(/^say: (.+)/i) | |
str = match[1] | |
msg(name, 'says', str) | |
require('child_process').spawn 'say', [str] | |
else | |
msg(name, 'sent', line) | |
require('dns').lookup require('os').hostname(), (err, add, fam) -> | |
server.listen(PORT) | |
terminal.color('green').write("Listening on IP: #{add} PORT: #{PORT}").reset().nl() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment