DEV Community

Dylan
Dylan

Posted on • Edited on

Exploring Different API Architecture Styles: Sockets

Sockets provide a way for bidirectional real-time communication between a client and a server. They are widely used in chat applications, online games, and live data streaming. Here's an example of how to implement a simple chat server using sockets in Node.js:

javascript

const net = require('net');

const server = net.createServer(socket => {
   console.log('Client connected');

   socket.on('data', data => {
     console.log('Message received:', data.toString());
     socket.write('Message received');
   });

   socket.on('end', () => {
     console.log('Client disconnected');
   });
});

server.listen(3000, () => {
   console.log('Chat server running on port 3000');
});

Enter fullscreen mode Exit fullscreen mode

In this example, we create a socket server that listens on port 3000 and handles client connections. When a client sends a message, the server receives it and responds with a confirmation message.

Socket Applications:

  • Real-time applications
  • Push notifications
  • Remote monitoring

Top comments (0)