bloc referral

If you are interested in learning to code with a mentor, try bloc and get $100 off.

Saturday, January 31, 2015

Making Custom User Names in Socket.io

A few months back I did a pairing session Chris Hunt and together we built a Node Chat app using the very convenient Getting Started Guide on Socket.io's doc page. We successfully completed the guide and deployed the app with minor hiccups.

Once a month here at work, we take part in a "hack day" where we can work on any project that is vaguely relevant to the business we are in or the company we work for. I took on the challenge to creating a new chat app and possibly implementing as a special feature at work.

One thing I noticed right after completing the app was the lack of user names displayed inline. While chatting with Chris on our app, it was easy to know which messages were not mine, but it would have been nice to know in case I needed to review the history.

Knowing the little node I knew I starting looking into the redis and socket.io-redis npm's and figure thats what I needed to save the username when prompted, but after a bit of time scaling the api and documentation it turned out it was only needed to save the printed chat messages for the session.

I was dissappointed when I did not find a blog post on the subject, but eventually found an old youtube video explaining exactly what I needed to know.

Each user can login with a session or socket and within each socket I needed to save their username. I was actually saving the username to late in the game and every message had the same user's name. I had to access the socket and save the username the same time as the message. Here is an example of the code:














*notice how I am prepending the chat name in the chat message while emitting the socket.

Here is the jQuery providing the chat in my view:

  












I create a new socket call to save my username that was collect from a javascript prompt and voila, the user's username got displayed each time they printed a message. I am pretty proud that I was able to complete and publish the chat app to heroku in time to present in our hack day presentation meeting.

*I made the dangerous decision of publicly displaying a chat to a projector screen.
















As far as redis, I only need that to save the previous chat messages, which for the purpose of my feature, it is not needed. There is still work to be done on the front end and how it will be render to make it a new feature, but I am pretty proud of this little guy - My Chat App.

1 comment: