设置报头web套接字



我想通过blob数据到java服务器使用web套接字。我的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);
}

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)

怎么了?帮助我。谢谢你。

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();

相关内容

  • 没有找到相关文章

最新更新