Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

add an example for a chat room, where the router routes each message …

…to all of the clients
  • Loading branch information...
commit 022b786fbb9f753e098a5412c4420b737ef5ea51 1 parent cbac0db
towski towski authored

Showing 1 changed file with 72 additions and 0 deletions. Show diff stats Hide diff stats

  1. +72 0 irc.js
72 irc.js
... ... @@ -0,0 +1,72 @@
  1 +// IM chat
  2 +// Binds a ROUTER socket on 5555
  3 +
  4 +require('tty').setRawMode(true);
  5 +
  6 +var context = require('zeromq')
  7 + , router = context.createSocket('router')
  8 + , request = context.createSocket('request')
  9 + , reply = context.createSocket('reply')
  10 + , name = process.env.NAME || process.env.USER
  11 + , connect_port = process.env.CONNECT_PORT || '5555'
  12 + , serve_port = process.env.SERVE_PORT || '5555'
  13 +
  14 +var peers = []
  15 +
  16 +router.on('message', function(from, msg) {
  17 + if(server){
  18 + var sender = from.toString();
  19 + if(peers.indexOf(sender) == -1){
  20 + peers.push(sender)
  21 + }
  22 + for(peer in peers){
  23 + router.send(peers[peer], sender + " " + msg.toString())
  24 + }
  25 + } else {
  26 + console.log(msg.toString());
  27 + }
  28 +})
  29 +
  30 +router.identity = name
  31 +console.log("Logging in as", name)
  32 +
  33 +var message = '',
  34 + lastuser = "towski",
  35 + match = null,
  36 + server = false
  37 +
  38 +process.stdin.on("data", function(buf) {
  39 + if(buf[0] == 13) {
  40 + var text = message.trim()
  41 + message = ''
  42 + if(text == '') return
  43 + if(text == 'q') {
  44 + console.log("Closing...")
  45 + process.stdin.pause()
  46 + router.close()
  47 + process.kill()
  48 + } else {
  49 + if(server){
  50 + for(peer in peers){
  51 + router.send(peer, text)
  52 + }
  53 + } else {
  54 + router.send("towski", text)
  55 + }
  56 + }
  57 + } else {
  58 + message += buf.toString()
  59 + }
  60 +})
  61 +
  62 +if(process.env.SERVE_PORT){
  63 + server = true
  64 + router.bind("tcp://*:5555", function() {
  65 + process.stdin.resume()
  66 + })
  67 +} else {
  68 + router.connect("tcp://localhost:5555")
  69 + process.stdin.resume()
  70 +}
  71 +
  72 +

0 comments on commit 022b786

Please sign in to comment.
Something went wrong with that request. Please try again.