1

我有一个 websocket 客户端代码,当我通过它上传文件时,web socket 服务器会接收该文件。但大小始终为零。我正在使用来自tootallnate 的Java-Websocket 服务器。下面是我的客户端代码。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Chat</title>
<script type="text/javascript" src="/MyHomePage/jquery-2.0.3.min.js">    </script>
</head>
<body>
  <h2>File Upload</h2>
   Select file
   <input type="file" id="filename" />
   <br>
<input type="button" value="Connect" onclick="connectChatServer()" />
<br>
<input type="button" value="Upload" onclick="sendFile()" />
<script>
    var ws;

    function connectChatServer() {
        ws = new WebSocket(
                "ws://localhost:8887/");

        ws.binaryType = "arraybuffer";
        ws.onopen = function() {
            alert("Connected.")
        };

        ws.onmessage = function(evt) {
            alert(evt.msg);
        };

        ws.onclose = function() {
            alert("Connection is closed...");
        };
        ws.onerror = function(e) {
            alert(e.msg);
        }

    }

    function sendFile() {
        var file = document.getElementById('filename').files[0];
        ws.send('filename:'+file.name);
        var reader = new FileReader();
        var rawData = new ArrayBuffer();            
        //alert(file.name);

        reader.loadend = function() {

        }
        reader.onload = function(e) {
            rawData = e.target.result;
            ws.send(rawData);
            alert("the File has been transferred.")
            ws.send('end');
        }

        reader.readAsArrayBuffer(file);

    }


</script>

下面是我的网络套接字服务器代码。

@Override
public void onMessage(WebSocket conn, String message) {
    System.out.println("received message from " + conn.getRemoteSocketAddress() + ": " + message);
    if (!message.equals("end")) {
        fileName = message.substring(message.indexOf(':') + 1);
        uploadedFile = new File(filePath + fileName);
        try {
            fos = new FileOutputStream(uploadedFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } else {
        try {
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void onMessage(WebSocket conn, ByteBuffer message) {
    System.out.println("Binary Data");

    while (message.hasRemaining()) {
        try {
            fos.write(message.get());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

请指教。

4

1 回答 1

0

如果文件大小大于缓冲区大小,您的解决方案将失败。

       function sendFile() { 
       var file = document.getElementById('filename').files[0];
            var start=0;
             var end=file.size;


             while(start < end){

                var next=start+8192;//8192 is buffer size
                if(end < next){
                 var blob1=file.slice(start,end);
                 websocket.send(blob1);
                 start=end;
                }else{
                var blob1=file.slice(start,next);
                 websocket.send(blob1);
                 start=next;
                }

                var stat=(start/end)*100;




             }

    }

使用 Web Workers 来实现 sendFile() 函数,因为浏览器会卡住。
在Server端第一次打开

          FileOutputStream fos= new FileOutputStream("Path");
           fc.write(message);
           conn.getUserProperties().put("FileChannel", fos.getChannel());

第二次

          FileChannel fc=conn.getUserProperties().get("FileChannel");
          fc.write(message);

最后关闭 FileChannel

于 2015-12-15T06:07:35.927 回答