我尝试从websocket服务器(使用ASP.NET服务器构建)异步接收到Android客户端的文本消息。我尝试了几个Android网络套接字库(autobahn、Android网络套接字、移动网络套接字、java网络套接字…),但Android客户端只有在之前发送消息后才会收到短信。我想从服务器(或另一个客户端)接收消息,而无需之前发送短信。
例如,你知道任何解决方案或聊天示例应用程序吗?
非常感谢!
(这是第二篇文章。第一篇在这里)
以下是我在高速公路库中使用的代码:
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());
}
}
我也从两周开始在Android上使用websocket。。。在我的情况下,我想使用WSS,所以,安全的websocket和自签名证书。。。在我的所有尝试中,唯一无缝工作的库是nv-websocket客户端,但这只是针对安全的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) {
}
}
}