我通过WebSockets实现Autobahn与服务器的连接。当我点击连接时,它会正确打开套接字并记录该套接字是否已打开。然后我尝试向服务器发送一个简单{"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接收数据。有人可以告诉我,如果我在这里做错了吗?
谢谢。
答案 0 :(得分:0)
我已经弄明白了我的问题。 WebSocket连接需要添加协议和选项。所以我改变了这个:
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());
}
到此:
mAutoBahnConnection.connect(mSocketHostAddress,new String[]{"this is my protocol"} ,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 onRawTextMessage(byte[] payload) {
try {
rawText = new String(payload, "UTF-8");
Log.i(m_TAG, "ON RAW TEXT");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void onBinaryMessage(byte[] payload) {
Log.i(m_TAG, "ON BINARY MESSAGE");
}
@Override
public void onClose(int code, String reason) {
Log.i(m_TAG, "Connection lost."+ reason);
}
}, options);
} catch (WebSocketException e) {
Log.d(m_TAG, e.toString());
}