Working with Sockets in Dart
Sockets are a means of two-way communication over a network. This is similar to HTTP communication, but instead of making a single request and getting a single response, you leave the channel open for further communication. This has applications in chat apps, database communication, and other real-time messaging applications.
A socket server can listen for and receive connections from multiple socket clients. The server can then broadcast messages to all of the connected clients or take a message from one client and forward it on to another.
In Dart you create a socket client using the Socket
class, and a socket server using the SocketServer
class. The next two sections will show you exactly how to do that. Rather than having the server broadcast or relay messages to lots of clients, though, you’ll just create a single client and server.
Socket server
Let’s make a knock knock joke server. It’ll answer knock knock jokes from clients who connect.
Create a new Dart project called socket_server:
dart create socket_server