我尝试从websocket服务器(使用ASP.NET服务器构建)接收异步文本消息到Android客户端。我尝试了几个Android websocket librairies(autobahn,android-websocket,mobile-websocket,java-websocket,...)但是android客户端只在之前发送消息后才收到短信。我希望从服务器(或其他客户端)接收消息,而无需在此之前发送文本消息。
您是否知道任何解决方案或聊天示例应用程序?
非常感谢!
(这是第二篇文章。第一篇是here)
这是我在autobahn lib中使用的代码:
private final WebSocketConnection mConnection = new WebSocketConnection();
private void start() {
final String wsuri = "ws://localhost:9000";
try {
mConnection.connect(wsuri, new WebSocketHandler() {
@Override
public void onOpen() {
mConnection.sendTextMessage("Hello, world!");
}
@Override
public void onTextMessage(String payload) {
// Here, I received message only if I have used WebSocketConnection.sendTextMessage(String) function
}
@Override
public void onClose(int code, String reason) {
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
}
答案 0 :(得分:0)
我开始在Android上使用websocket两周了......在我的情况下我想使用WSS,所以,安全的websockets和自签名证书......我所有的尝试都是唯一能无缝工作的库是nv-websocket-client,但这只是针对安全的websocket案例。
无论如何,如果你发现它有用,我把你的代码放在这里,我删除了一些隐私细节,如果你需要一个简单的连接,你可以跳过SSL部分。
public class SocketHandler
{
private final static String LOGTAG = "SocketHandler";
private int TIMEOUT = 5000;
private MainActivity main;
private SocketConnector socketConnector;
public SocketHandler(MainActivity main) {
this.main = main;
}
public void connect() {
socketConnector = new SocketConnector();
socketConnector.execute();
}
public void disconnect() {
socketConnector.ws.disconnect();
}
private class SocketConnector extends AsyncTask<Void, Void, Void> {
WebSocket ws;
@Override
protected Void doInBackground(Void... params) {
try {
SSLContext context = NaiveSSLContext.getInstance("TLS");
WebSocketFactory wsf = new WebSocketFactory();
wsf.setConnectionTimeout(TIMEOUT);
wsf.setSSLContext(context);
ws = wsf.createSocket("wss://" + ADDRESS);
ws.addListener(new WSListener());
ws.addExtension(WebSocketExtension.parse(WebSocketExtension.PERMESSAGE_DEFLATE));
ws.connect();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
private class WSListener extends WebSocketAdapter {
@Override
public void onConnected(WebSocket websocket, Map<String, List<String>> headers) {
websocket.sendText("Hello World");
}
@Override
public void onTextMessage(WebSocket websocket, String message) {
}
@Override
public void onError(WebSocket websocket, WebSocketException cause) {
}
}
}