Live Web / Socket.io – Lame Chat

As a practice for using socket.io, I made a lame chat deliberately, limiting the choice of words to use. Using twitter streaming API, the app will give you choice of around 200 words from recent twitter within NYC area. You can make a sentence by clicking buttons of words one by one. Still it’s in pretty much conceptual stage, but it might become intriguing app to play with if it’s further developed.

Screen Shot 2017-09-19 at 1.06.00 AM

//server.js

// Twitter part
var Twit = require('twit')

var T = new Twit({
  consumer_key: "ufDGsqlymEGNVLe1aws4H36D1",
  consumer_secret: "LO1Ue4ylzgLFx5AgKR0ABi1bLtBO9HKww5sxbkiwQjqRK5ubyY",
  access_token: "836034020173623296-kfxoDIqip2rhByuadNEgEEANWMOjCl8",
  access_token_secret: "nwhboLj5z6l62cRLdJY9ME3H2Wz7RO8YJRz9EyJdm1C4g",
  timeout_ms: 60 * 1000, // optional HTTP request timeout to apply to all requests.
})

var finalWords = [];

function getTweet() {
  // filter the public stream by the latitude/longitude bounded box of NYC
  var nyc = ['-74.2591', '40.4774', '-73.7002', '40.9162']
  var stream = T.stream('statuses/filter', {
    locations: nyc
  })

  stream.on('tweet', function(tweet) {
    var text = tweet.text;
    text = text.split('http')[0];
    text = text.split('RT')[0];
    text = text.split('@')[0];
    if (text !== "") {
      var words = text.split(' ');
      Array.prototype.push.apply(finalWords, words);
    }
    console.log(finalWords);
    console.log(finalWords.length);

    if (finalWords.length >= 200) {
      stream.stop()
      console.log('stopped');
    }
  })
}


// Chat server part

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket) {
  getTweet();
  console.log("We have a new client: " + socket.id);

  // Send picked words to client
  io.emit('selectedWords', finalWords)

  socket.on('disconnect', function() {
    console.log('user disconnected');
  });

  // Share messages to all
  socket.on('chat message', function(data) {
    console.log("Received: 'chat message' " + data);
    io.emit('chat message', data);

  });
});


http.listen(3000, function() {
  console.log('listening on *:3000');
});
// index.html 


<!doctype html>
<html>

<head>
  <script src="/socket.io/socket.io.js"></script>
  <title>NYC Lame Chat</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font: 13px Helvetica, Arial;
    }

    #sendButton {
      width: 100%;
      height: 20px;
      font-size: 13px;
      background: lightgray;
    }

    .wordButton {
      height: 20px;
      font-size: 13px;
    }

    #messageSection {
      width: 100%;
      height: 400px;
      background: black;
      color: white;
      word-wrap: break-word;
      overflow-wrap: break-word;
      font-size: 15px;
    }


    #buttonSection {
      text-align: center;
    }
  </style>
</head>

<body>
  <div id="messageSection"></div>
  <div id="inputSection">
    <div id="buttonSection">
    </div>
    <button id="sendButton" onclick="sendMessage()"> send </button>
  </div>

  <script>
    var socket = io();

    socket.on('connect', function() {
      console.log("Connected");
    });

    // Receive words from recent tweets in NYC
    socket.on('selectedWords', function(data) {
      console.log(data);
      for (var i = 0; i < data.length; i++) {
        var text = document.createTextNode(data[i]);
        if (text !== "") {
          var button = document.createElement("button");
          button.setAttribute("class", "wordButton")
          button.appendChild(text);
          button.addEventListener('click', addWords);
          document.getElementById("buttonSection").appendChild(button);
        }
      }
    });

    // Receive message
    socket.on('chat message', function(data) {
      console.log(data);
      document.getElementById('messageSection').innerHTML = document.getElementById('messageSection').innerHTML + " " + data;
    });

    // Put a word on server when choosing(clicking) it.
    function addWords() {
      console.log("chat message: " + this.innerHTML);
      socket.emit('chat message', this.innerHTML);
    }

    // Divide messages by adding line breaker. 
    function sendMessage() {
      console.log("send message");
      socket.emit('chat message', "< <br /><br />");
    }
  </script>

</body>

</html>

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *