使用websocket javascript客户端发送文件

时间:2015-01-15 08:10:00

标签: java javascript spring websocket

我尝试使用websocket连接向我的服务器发送文件: 我使用java Spring实现了websocket服务器端 客户端是在javaScript中 出于某种原因,每次我使用" blob"从客户端发送二进制消息或" arraybuffer。服务器将消息识别为文本消息而不是二进制文件。 我在这里失踪了什么?

客户端

 <!DOCTYPE HTML>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <title>Chat</title>
        </head>
    <body>
        <h2>File Upload</h2>
            Select file
        <input type="file" id="filename" />
        <br><br><br>
        <input type="button" value="Connect" onclick="WebSocketTest()" />
        <br><br><br>
        <input type="button" value="Upload" onclick="sendFile()" />

    <script>
    "use strict"
    var ws;
    function WebSocketTest()
    {
      if ("WebSocket" in window)
      {
         console.log("WebSocket is supported by your Browser!");
         // Let us open a web socket
         ws = new WebSocket("ws://xx.xx.xx.xx:yyyy/service/audioHandler");
         ws.onopen = function()
         {
            // Web Socket is connected, send data using send() 
            ws.send(JSON.stringify({userName:'xxxx',password:'sgdfgdfgdfgdfgdf'}));
            console.log("Message is sent...");
         };
         ws.onmessage = function (evt)
         {
            var received_msg = evt.data;
            console.log("Message is received...");
         };
         ws.onclose = function()
         {
            // websocket is closed.
            console.log("Connection is closed...");
         };
      }
      else
      {
         // The browser doesn't support WebSocket
         console.log("WebSocket NOT supported by your Browser!");
      }
    }

function sendFile() {
    var file = document.getElementById('filename').files[0];
    ws.binaryType = "arraybuffer";
    //ws.send('filename:'+file.name);
    var reader = new FileReader();
    var rawData = new ArrayBuffer();           
    console.log(file.name);
    reader.loadend = function() {
    }
    reader.onload = function(e) {
        rawData = e.target.result;
        ws.send(rawData);
        console.log("the File has been transferred.")
        //ws.send('end');
    }
    reader.readAsArrayBuffer(file);
}   
</script>
</body>
</html>

服务器端

public class WebSocketController extends BinaryWebSocketHandler {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private CallScopeStore callScopeStore;

    private static Logger logger = Logger.getLogger(AudioHandler.class);
    private static final String STOP_MESSAGE = "stop";

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
        try {
         //do something....
        } catch (Exception e) {
            logger.error(e, e);
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void handleTextMessage(final WebSocketSession session, TextMessage message) {
        try {
            //do something....
            }
        } catch (Exception e) {
            logger.error(e, e);
            throw new RuntimeException(e);

        }
    }
}

2 个答案:

答案 0 :(得分:1)

您必须将文件作为blob发送。

ws = new WebSocket("ws://xx.xx.xx.xx:yyyy/service/audioHandler");
ws.binaryData = "blob";
ws.send(message); // Blob object

正如您所提到的,您可能会发现错误:&#34; CloseStatus [code = 1009,reason = No async message support and buffer too small。缓冲区大小:[8,192],邮件大小:[7,816,684]]&#34;。这是因为您的WebSocket引擎需要配置为允许具有您想要的大小的二进制消息。例如,在您的WebSocketConfig中:

@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
    ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
    container.setMaxTextMessageBufferSize(500000);
    container.setMaxBinaryMessageBufferSize(500000);
    return container;
}

如您所见,您可以设置文本和二进制消息允许的最大大小,只需指定大于7,816,684的大小(您尝试发送的文件)。默认情况下,您的缓冲区大小为[8,192],因此如果您发送的文件大小小于缓冲区大小,则不应该出现问题。有关详细信息,请查看websocket spring documentation

答案 1 :(得分:1)

@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
    ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
    container.setMaxTextMessageBufferSize(500000);
    container.setMaxBinaryMessageBufferSize(500000);
    return container;
}

WebSocketMessageBroker无效。 @ robert08

@Configuration
@EnableWebSocketMessageBroker
public class MyWebSocketMessageBrokerConfigurer implements WebSocketMessageBrokerConfigurer {


    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/portfolio").setAllowedOrigins("*");
    }


    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.setPathMatcher(new AntPathMatcher("."));
        config.setApplicationDestinationPrefixes("/app");
        config.enableSimpleBroker("/topic", "/queue");
    }


    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration webSocketTransportRegistration) {
        webSocketTransportRegistration
                .setMessageSizeLimit(1024 * 1024)
                .setSendBufferSizeLimit(1024 * 1024 );

    }


}