javajavax。websocketclient:如何将大型二进制数据从clientendpoint发送到serverendpoint
我正在尝试使用jetty构建一个服务器客户端应用程序。我已经安装了jetty服务器并配置了WebSocket。在客户端和服务器之间发送文本消息工作正常。但如何将二进制数据作为inputstream从客户端端点发送。我找不到任何关于websocket客户端的代码片段。下面是我尝试过的
服务器端点:
@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();
}
客户点:
@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);
}
}
谢谢你的帮助
编辑:
我已经修改了clientendpoint和serverendpoint。试图以块的形式发送数据,但zip文件是部分的,有时甚至比源文件小
源大小:1.5gb 使用流从缓冲区写入数据后:20kb
@ClientEndpoint
private static void sendFileToRemote(File source) throws FileNotFoundException, IOException {
// TODO Auto-generated method stub
Session session=null;
final WsClient wc = new WsClient("ws://localhost:2714/events/","test");
session=wc.getSession();
try (
InputStream inputStream = new FileInputStream(source);
) {
byte[] chunk = new byte[102400];
int chunkLen = 0;
while ((chunkLen = inputStream.read(chunk)) != -1) {
session.getAsyncRemote().sendBinary(ByteBuffer.wrap(chunk, 0, chunkLen));
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
@serverendpoint
@ServerEndpoint("/events/")
public class EventListener {
static Logger logger = Logger.getLogger(Initservice.class.getName());
private OutputStream os=null;
@OnOpen
public void Init(Session session) throws FileNotFoundException {
this.user_session = session;
logger.info("onOpen:: server" + session.getId());
this.os = new FileOutputStream(new File("/tmp/silicon_test.zip"));
logger.info("instantiate zip files");
}
@OnMessage
public void onMessage(Session session, ByteBuffer byteBuffer) throws IOException {
try {
os.write(byteBuffer.get());
} catch(Exception e) {
close();
logger.log(Level.SEVERE,"Exception occured in onMessage :: ", e);
throw e;
}
}
}
# 1 楼答案
ServerEndpoint中的代码看起来应该可以正常工作,但是在ClientEndpoint中,您只向ServerEndpoint发送文本数据,并且这只能由配置为接收文本消息的server onMessage方法读取
您应该使用方法
session.getRemoteEndpoint().sendBinary(...)
,而不是使用session.getRemoteEndpoint().sendText(...)
。这将以二进制帧而不是文本帧的形式发送数据,您将能够在服务器handleBinaryMessage
方法中接收数据至于
session.getAsyncRemote().sendObject(input)
,为了实现这一点,您还需要提供Encoder.Binary
或Encoder.BinaryStream
,以便将对象作为二进制数据发送编辑:
WebSocket是一种基于消息的协议,您通过多条WebSocket消息从文件发送数据。您可以使用
session.getBasicRemote().sendBinary(ByteBuffer, boolean)
发送部分消息,并在同一消息中发送所有数据或者您可以尝试类似于此代码的更简单的代码