2

我想使用 web socket 将 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)

怎么了?帮我。谢谢你。

4

1 回答 1

4

ObjectInputStream的文档说:

ObjectInputStream 反序列化以前使用 ObjectOutputStream 编写的原始数据和对象...

您尝试从 JavaScript 程序发送的随机 BLOB 不符合“以前使用 ObjectOutputStream 编写的原始数据和对象”的条件,因此,无论您尝试使用 BLOB 做什么,它都行不通。

您想要做什么最终取决于您将使用 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();
于 2013-05-08T18:51:03.153 回答