javax.websocketclient:如何从客户端端点向服务器端点发送大型二进制数据

问题描述 投票:0回答:1

我正在尝试使用码头来构建服务器客户端应用程序。我已经设置了一个码头服务器并配置了websockets。在客户端和服务器之间发送文本消息可以正常工作。但是如何从客户端端点发送二进制数据作为输入流。我找不到有关websocket客户端的任何摘要。以下是我尝试过的内容

ServerEndPoint:

   @OnMessage
   public void handleBinaryMessage(InputStream input, Session session) {

       logger.info("onMessage::inputstream");

       try {

        byte[] buffer = new byte[2048];
        try (OutputStream output = session.getBasicRemote().getSendStream())
        {
            int read;
            while ((read = input.read(buffer)) >= 0)
                output.write(buffer, 0, read);
        }

    } catch (IOException e) {
      e.printStackTrace();
    }

ClientEndpoint:

@OnOpen 
public void onOpen(Session s) throws IOException {
  logger.info("Client Connected ... " + s.getId());
  this.session=s;

  session.getBasicRemote().sendText("Ping from client");

  // size of the file 200~500MB
  File source= new File("/tmp/Setup.exe");

  try(InputStream input = new FileInputStream(source)) {


              session.getAsyncRemote().sendObject(input);


            }

}        

感谢您的任何帮助

java websocket jetty java-websocket jsr356
1个回答
0
投票

ServerEndpoint中的代码看起来应该可以正常工作,但是在ClientEndpoint中,您仅将文本数据发送到ServerEndpoint,并且只能由配置为接收文本消息的服务器onMessage方法读取。

而不是使用session.getRemoteEndpoint().sendText(...),而应使用方法session.getRemoteEndpoint().sendBinary(...)。这将以二进制帧而不是文本帧发送数据,您将可以在服务器的handleBinaryMessage方法中接收它。

关于session.getAsyncRemote().sendObject(input),要完成此工作,您还需要提供Encoder.BinaryEncoder.BinaryStream以便将对象作为二进制数据发送。

© www.soinside.com 2019 - 2024. All rights reserved.