Socket.io 聊天应用程序,也可以发送图像甚至文件

Socket.io chat app that can also send image and even file

本文关键字:图像 文件 也可以 io 聊天 应用程序 Socket      更新时间:2023-09-26

我最近对Socket.io项目很感兴趣,我想知道是否有简单的方法可以在不使用其他库的情况下发送图像甚至其他类型的文件。我不是想把文件上传到服务器存储,我只是想把它广播给当时在聊天室里的人。所以代码应该是最小的。但是,我真的很不擅长编码/解码东西,所以一些示例代码会很棒。

我改编了 Socket.io 的官方聊天示例,并增加了通过base64编码发送文件/图像甚至视频的功能,您可以查看client.jsindex.js的源代码,以下是最相关的部分,希望对您有所帮助。

在客户端:

$('#uploadfile').bind('change', function(e){
    var data = e.originalEvent.target.files[0];
    readThenSendFile(data);      
});
function readThenSendFile(data){
    var reader = new FileReader();
    reader.onload = function(evt){
        var msg ={};
        msg.username = username;
        msg.file = evt.target.result;
        msg.fileName = data.name;
        socket.emit('base64 file', msg);
    };
    reader.readAsDataURL(data);
}

在服务器端:

socket.on('base64 file', function (msg) {
    console.log('received base64 file from' + msg.username);
    socket.username = msg.username;
    // socket.broadcast.emit('base64 image', //exclude sender
    io.sockets.emit('base64 file',  //include sender
        {
          username: socket.username,
          file: msg.file,
          fileName: msg.fileName
        }
    );
});

这是项目:

https://github.com/Arch1tect/Chatbox