Chapter 18. A chat app using sockets
This chapter covers
- Creating a socket server
- Connecting to a socket server
- Using TCP and UDP sockets
Higher-level networking approaches such as SOAP and RESTful services are great when you don’t need to count milliseconds or when communication is primarily one way. But what about those times when you need to perform near real-time control of, say, a robot? How about synchronizing character or object movement for a game? Those are all performance-critical, often bidirectional, and sometimes peer-to-peer communications scenarios.
When apps need to communicate across a network as quickly and efficiently as possible, they use sockets. Socket communication is two-way communication between, in most cases, two endpoints. (Multicast/broadcast socket is the one-to-many or even many-to-many approach used in some other scenarios. I won’t cover those approaches here because they aren’t as commonly used, but I do build on the normal socket communication in this chapter.)
Sockets are what power the internet. Protocols such as HTTP are built on top of socket communication. Whenever you specify a port, you’re specifying an endpoint for a socket, with the additional protocol built on top of it. If you want to implement your own protocol, you’ll almost certainly start with socket communication.