[英]Set header web socket?
I want pass blob data to java server using web socket. 我想使用Web套接字将Blob数据传递给Java服务器。 My java server is: 我的Java服务器是:
providerSocket = new ServerSocket(2007, 10);
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
And my javascript client is: 我的JavaScript客户端是:
var ws = new WebSocket("ws://127.0.0.1:2007");
ws.binaryType = "blob";
ws.onopen = function () { console.log("Openened connection to websocket"); };
ws.onmessage = function(e) {
console.log(e.data);
};
function doneEncoding( blob ) { // blob is audio blob
ws.send(blob);
}
Error is: in server 错误是:在服务器中
Connection received from 127.0.0.1
java.io.StreamCorruptedException: invalid stream header: 47455420
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at server.Provider.run(Provider.java:21)
at server.Provider.main(Provider.java:67)
Exception in thread "main" java.lang.NullPointerException
at server.Provider.run(Provider.java:43)
at server.Provider.main(Provider.java:67)
What is wrong? 怎么了? Help me. 帮我。 Thank you. 谢谢。
The docs for ObjectInputStream say: ObjectInputStream的文档说:
An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream ... ObjectInputStream反序列化原始数据和先前使用ObjectOutputStream编写的对象。
A random BLOB you are trying to send from a JavaScript program doesn't qualify as "primitive data and objects previously written using ObjectOutputStream" so, whatever you're trying to do with the BLOB, it's not gonna work. 您尝试从JavaScript程序发送的随机BLOB不符合“以前使用ObjectOutputStream编写的原始数据和对象”的条件,因此,无论您试图对BLOB进行什么操作,它都行不通。
What you want to do depends ultimately on what you are going to use the BLOB for, but you may want to read it into a byte array or something similar, as in: 最终,您要做什么取决于要使用BLOB的内容,但是您可能希望将其读入字节数组或类似的内容,例如:
InputStream in = connection.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int n;
for (n = in.read(buffer); 0 < n; n = in.read(buffer))
{
out.write(buffer, 0, n);
}
out.flush();
byte[] blob = out.toByteArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.