如何在与SocketIO,NodeJS和express的聊天中提供发送和接收文件(图像,声音,视频)?

时间:2018-10-21 18:36:16

标签: javascript node.js express socket.io streaming

这是我已经尝试过的代码。当用户尝试发送时,出现“未指定的错误”,页面会重新加载自身(导致显示loginDiv)。

index.js(请参见/////相关部分///):

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

http.listen(3000, function(){
  console.log('listening on *:3000');
});

io.on('connection', function(socket){
  socket.on('user login', function(newuser){
    var validUsername=false;
    if(users.includes(newuser)){
      validUsername = false;
    }else {
      console.log('user: '+ newuser + ' logged in.');
      socket.username = newuser; users.push(newuser);
      connectedSockets[socket.username]=socket.id; //assigning socket id to socket username to find id easier later
      updateUsers();
      validUsername=true;
    };
    socket.emit('validate username', {valid: validUsername});
  });

  socket.on('disconnect', function(){
    if(socket.username!=undefined){
      delete connectedSockets[socket.username];
      deleteUser(socket.username);
    }
  });

  /**
  * Public Message to all users.
  * Sends received message to all users, including the sender with timestamp and sendername.
  * */
  socket.on('public message', function(data){
    io.emit('public message', {from: socket.username, msg: data.msg });
  });

/////////RELEVANT PART//////////////
  socket.on('base64 file', function (msg) {
    console.log('received base64 file from' + msg.username);
    socket.username = msg.username;

    io.emit('base64 file',
        {
          username: socket.username,
          file: msg.file,
          fileName: msg.fileName
        }
    );
});

index.html(请参阅/////相关部分//):

    <!--Login Area-->
    <div id="loginDiv"> <h1>Welcome to Mchat!</h1>
        <form action="" id="enterName">
          <p id="userNameText">    Username:</p>
          <input id="userNameInput" placeholder="Enter a username" autocomplete="off" required/>
          <button id="loginButton">Enter Mchat</button>
        </form>
    </div>
    <!--Login Area End-->

<!--Message Area-->
<div id="chatDiv" style="display: none">
  <div id="messageDiv" style="float:left">
    <ul id="messages"></ul>
    <form action="" id="onSend">
        <input id="messageInput" placeholder="type a message" autocomplete="off" required/>
        <input id="fileChooser" type="file" > 
        <!-- <input id="fileChooser" multiple type="file"> -->
        <button id="sendMButton">Send</button>
    </form>
  </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
    $(function () {
        var socket = io();
        $('#enterName').submit(function () {
           socket.emit('user login',$('#userNameInput').val());
           return false;
        });

        socket.on('validate username', function(validation){
            if(validation.valid==true){
              $('#loginDiv').hide(); 
              $('#chatDiv').show();
            }
            else {
              alert("This username is already assigned to another user! Please enter a different username.");
            }
            $('#userNameInput').val('');  

        });

        $('#onSend').submit(function(){
            // socket.emit('public message', {
            //     msg:$('#messageInput').val(),
            //     // file: $('#fileChooser').val()  
            //     file: $('#fileChooser').files[0]
            // })
            var data={};
            data.msg=$('#messageInput').val();
            // data.file=readFile($('#fileChooser').files[0]);
            socket.emit('public message', data)

/////RELEVANT PART////////
                var fileChooser=$('#fileChooser');
                if(fileChooser.files[0]!=undefined){
                    console.log("there is a file");
                    readThenSendFile(fileChooser.files[0])
                }

                $('#messageInput').val(''); $('#fileChooser').val('')
                return false;
            });

        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(data){
            console.log(data.fileName)
        })
///////RELEVANT PART ENDS
        socket.on('public message', function(data){
            //$('#messages').append($('<li>'+data.timestamp + ' - <span class="greyText">' + data.from + '</span>: ' + data.msg+" "+data.file+'</li>'));
$('#messages').append($('<li>'+data.timestamp + ' - <span class="greyText">' + data.from + '</span>: ' + data.msg+'</li>'));
                window.scrollTo(0, document.body.scrollHeight);
            });
            }

    </script>

我也使用模块delivery.js进行了尝试,但结果相同:“ SCRIPT16389:未指定错误”。

0 个答案:

没有答案