How to Build a Concurrent Chat App With Golang and WebSockets
Build a real-time chat app with Go
Go emerged from Google out of a need to build highly performant applications using an easy-to-understand syntax. It’s a statically typed, compiled language developed by some of the innovators of C, without the programming burden of manual memory management. Primarily, it was designed to take advantage of modern multicore CPUs and networked machines.
In this article, I’ll demonstrate the capabilities of Go. We’ll take advantage of Go’s ability to easily create concurrent apps to build a chat app. On the back end, we’ll use Redis as the intermediary to accept messages from the browser and send them to the subscribed clients. On the front end, we’ll use WebSockets via socket.io to facilitate client-side communication. We’ll deploy it all on Heroku, a PaaS provider that makes it easy to deploy and host your apps. Just as Go makes programming such an application simple, Heroku makes it easy to supplement it with additional infrastructure.
Channels in Go
What developers find appealing about Go is its ability to communicate concurrently, which it does through a system called channels. It’s important to draw upon an oft-cited distinction between concurrency and parallelism. Parallelism is the process by which a CPU executes multiple tasks at the same time, while concurrency is the CPU’s ability to switch between multiple tasks that start, run, and complete while overlapping one another. In other words, parallel programs handle many operations at once, while concurrent programs can switch between many operations over the same period of time.
A channel in Go is the conduit through which concurrency flows. Channels can be unidirectional — with data either sent to or received by them — or bidirectional, which can do both. Here’s an example that demonstrates the basic principles of concurrency and channels: