gpt4 book ai didi

javascript - 来自 JavaScript Websocket 的 InputStream Java 未收到完整消息

转载 作者:太空宇宙 更新时间:2023-11-04 12:05:19 25 4
gpt4 key购买 nike

我有以下设置:Index.html(网页)

    <div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
<a href="javascript:websocketsend()">Send message</a>
</div>

<script type="text/javascript">
var ws;
function WebSocketTest()
{
if ("WebSocket" in window)
{
console.log("WebSocket is supported by your Browser!");

// Let us open a web socket
ws = new WebSocket("ws://localhost:6790/");

ws.onopen = function()
{
// Web Socket is connected, send data using send()

ws.send("Hello_World!");
console.log("Message is sent...");

};

ws.onmessage = function (evt)
{
var received_msg = evt.data;
console.log("Message is received...");
};

ws.onclose = function(event)
{
var reason;
// websocket is closed.
console.log(event.code);
console.log("closed.")
}

ws.onerror = function (evt)
{
console.log(evt);
}
}

else
{
// The browser doesn't support WebSocket
console.log("WebSocket NOT supported by your Browser!");
}
}
</script>

Java 套接字服务器

private String decodeMessage(InputStream in) {
Main.debug(in + "");
try {
in.skip(2);
ArrayList<Byte> keys = new ArrayList<Byte>();
for(int i = 0; i < 4; i++){
int r = in.read();
Main.debug("added: " + r);
keys.add((byte) r);
}

ArrayList<Byte> encoded = new ArrayList<Byte>();
for(int i = 0; i < in.available(); i++){
int r = in.read();
Main.debug("added2: " + r);
encoded.add((byte) r);
}

ArrayList<Byte> decoded = new ArrayList<Byte>();
for(int i = 0; i < encoded.size(); i++){
decoded.add((byte) (encoded.get(i) ^ keys.get(i & 0x3)));
Main.debug("Decoded: " + (encoded.get(i) ^ keys.get(i & 0x3)));
}

Main.debug("Total: " + decoded);
String s = new String(toByteArray(decoded), "US-ASCII");
Main.debug("Text: " + s);

} catch(IOException e) {

}

return null;
}

public static byte[] toByteArray(List<Byte> in) {
final int n = in.size();
byte ret[] = new byte[n];
for (int i = 0; i < n; i++) {
ret[i] = in.get(i);
}
return ret;
}

问题是消息传递得很好,但是我将其作为输出(除了“添加”和“解码”调试消息之外,

[19:42:02 信息]:总计:[72, 101, 108, 108, 111, 95][19:42:02 INFO]:文本:Hello_

所以“世界!”即使我用空格替换_,也会丢失。有什么我忽略的事情吗?

希望有人可以在这里给我提示。提前致谢!

最佳答案

然后将其转换为 DataInputStream

while(datainputstream.available() > 0){
....
}

看来已经解决了!感谢@Tinus 帮助我找到这个解决方案!

关于javascript - 来自 JavaScript Websocket 的 InputStream Java 未收到完整消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40429883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com