我想使用web套接字将blob数据传递给java服务器。 我的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");
我的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);
}
错误是:在服务器
中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)
有什么问题?帮我。谢谢。
答案 0 :(得分:4)
ObjectInputStream的文档说:
ObjectInputStream反序列化原始数据和以前使用ObjectOutputStream编写的对象 ...
您尝试从JavaScript程序发送的随机BLOB不符合“原始数据和以前使用ObjectOutputStream编写的对象”,因此,无论您尝试使用BLOB做什么,它都无法正常工作。
你想做什么最终取决于你将使用BLOB的目的,但你可能想要read it into a byte array或类似的东西,如:
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();