我的游戏有问题。我正在用WebGL的Unity3D 5开发游戏。游戏使用 Web 套接字连接到服务器,其地址如下所示:
wss://serveraddress:8443/moreaddress
它使用 javascript 实现连接到服务器。javascript看起来像这样:
var WSClient = {
socket: null,
url: null,
connect: function(host) {
if ('WebSocket' in window) {
this.socket = new WebSocket(host);
} else if ('MozWebSocket' in window) {
this.socket = new MozWebSocket(host);
} else {
Console.log('Error: WebSocket is not supported by this browser.');
return;
}
this.socket.onopen = function()
{
SendMessage("WebSocketManager","OnOpenWebSocket");
};
this.socket.onclose = function() {
SendMessage("WebSocketManager","OnCloseWebSocket");
};
this.socket.onmessage = function(message) {
if(typeof message == "string"){
SendMessage('WebSocketManager','OnMessageReceived', message);
}
};
},
initialize: function(url) {
if (typeof url !== "undefined")
this.url = url;
if (this.url == null) {
Console.log('Info: Initialize without an URL');
return;
}
this.connect(this.url);
},
sendMessage: function(msg) {
if (msg != '') {
this.socket.send(msg);
}
},
close: function() {
this.socket.close();
}
};
SendMessage 函数只是在 Unity 中调用函数的东西。所以基本上发生在我身上的是在我的游戏连接到服务器后,onOpen()
函数被调用,然后从 Unity 调用我的OnOpenWebSocket()
函数,然后尝试向服务器发送消息登录,服务器收到消息并尝试向我发送答案,但我在onMessage()
函数中得到的只是这条消息: {"isTrusted":true}.
这发生在Firefox上,但在Chrome上运行良好。在 Chrome 上,我从服务器收到正确的消息。而且服务器中没有任何地方可以写入isTrusted
。
我正在使用火狐 33.0。和铬 39.0.2171.95
我查看了火狐浏览器的about:config
,websocket
已启用。
有人知道什么可能导致这种情况吗?
我在尝试 websocket 时遇到了同样的问题。我将代码更改为
var ws = new WebSocket("ws://localhost:3331"); // some url
ws.onmessage = function(event) {
console.log(event.data);
}
然后它在火狐上工作了!onmessage 回调的类型是 EventListener,并接收 MessageEvent 作为参数,请参阅 https://developer.mozilla.org/en-US/docs/Web/API/WebSocket。