我正在实现 Autobahn 以通过 WebSockets 连接到服务器。当我点击连接时,它会正确打开套接字并记录该套接字已打开。然后我尝试向服务器发送一个请求,这很简单{"request":"getSoftwareVersion"}
,当服务器收到这个请求时,它应该以 JSON 对象的形式发回软件版本,问题是,onMessage 永远不会被命中。这是我的代码:
public class AutoBahnConnectRequest extends Request{
private static WebSocketConnection mAutoBahnConnection;
private String mSocketHostAddress;
private final static String m_TAG = AutoBahnConnectRequest.class.getSimpleName();
public AutoBahnConnectRequest(String SocketHostAddress){
this.mAutoBahnConnection = new WebSocketConnection();
this.mSocketHostAddress = SocketHostAddress;
}
@Override
protected Void doInBackground(Void... params){
try {
mAutoBahnConnection.connect(mSocketHostAddress, new WebSocketHandler(){
@Override
public void onOpen() {
String requestSoftware = "{\"request\":\"getSoftwareVersion\"}";
Log.i(m_TAG, requestSoftware);
Log.i(m_TAG, "Status: Connected to " + mSocketHostAddress);
mAutoBahnConnection.sendTextMessage(requestSoftware);
}
@Override
public void onTextMessage(String payload) {
Log.i(m_TAG, "Got echo: " + payload);
}
@Override
public void onClose(int code, String reason) {
Log.i(m_TAG, "Connection lost."+ reason);
}
});
} catch (WebSocketException e) {
Log.d(m_TAG, e.toString());
}
return null;
}
}
这已经用一个像这样的 html 客户端实现了(不是用高速公路):
function getSoftwareVersion() {
socket_di.send('{"request":"getSoftwareVersion"}');
}
并且 onMessage 接收数据。如果我在这里做错了什么,有人可以告诉我吗?
谢谢你。