ArticleZip > Socket Io Node Js Simple Example To Send Image Files From Server To Client

Socket Io Node Js Simple Example To Send Image Files From Server To Client

Socket.IO and Node.js are powerful tools that can greatly enhance communication between a server and a client. In this article, we'll explore a simple example to send image files from a server to a client using Socket.IO and Node.js. By the end, you'll have a better understanding of how these technologies work together to transfer image files seamlessly.

First and foremost, make sure you have Node.js installed on your system. If you haven't already done so, head over to the Node.js website and download the latest version. Once Node.js is installed, you can easily set up a simple server using the following code:

Plaintext

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

http.listen(3000, () => {
  console.log('Listening on port 3000');
});

In this code snippet, we are setting up a basic Express server that serves an HTML file called `index.html`. We are also creating a Socket.IO server that will enable real-time communication between the server and the client.

Next, create an `index.html` file in the same directory as your server file and add the following code:

Html

<title>Socket.IO Image Transfer</title>


  <h1>Image Transfer Example</h1>
  <img id="image" src="#" />
  
  
    const socket = io();
    socket.on('image', (data) =&gt; {
      document.getElementById('image').src = `data:image/png;base64,${data}`;
    });

This HTML file contains a simple placeholder for displaying the image that will be sent from the server to the client. We also include the Socket.IO client script to establish a connection with the Socket.IO server.

Now, let's modify the Node.js server code to handle the image transfer:

Javascript

const fs = require('fs');

io.on('connection', (socket) =&gt; {
  fs.readFile('image.png', (err, data) =&gt; {
    socket.emit('image', data.toString('base64'));
  });
});

In this code block, we're reading an image file called `image.png` using the Node.js `fs` module and sending it to the client as a base64-encoded string when a client connects to the Socket.IO server.

To run the server, execute the command `node server.js` in your terminal. You can then access the server by navigating to `http://localhost:3000` in your web browser.

By following these steps, you've successfully set up a simple example of sending image files from a Node.js server to a client using Socket.IO. Feel free to experiment further and enhance this example to suit your specific needs!