我正在使用模拟网络服务器创建一个websocket服务器,并使用webview加载索引URL,以便客户端将向我发送一条消息,然后将一些数据发送回并登录。每次加载索引URL时,客户会给我发消息。现在的问题是,我单击索引URL的按钮并跳到另一页,然后再返回索引URL,我没有收到消息。
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
ButterKnife.bind(this);
initWebView();
Log.e("MrXieXie---Server", "onCreate");
new Thread(new Runnable() {
@Override
public void run() {
Server();
Log.e("MrXieXie---Server", "run");
}
}).start();
}
private void initWebView() {
WebSettings webSettings = webView.getSettings();
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return true;
}
});
webView.loadUrl("http://xxxxxxxx");
}
private void Server() {
mockWebServer.enqueue(new MockResponse().withWebSocketUpgrade(new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
Log.e("MrXieXie---Server", "WebSocketServer ===== onOpen");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
Log.e("MrXieXie---Server", "WebSocketServer ===== onMessage ===" + text);
if(!text.isEmpty() && text.equals("USER")){
webSocket.send("xxxx");
}
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
Log.e("MrXieXie---Server", "WebSocketServer ===== onMessage ===" + bytes);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
Log.e("MrXieXie---Server", "WebSocketServer ===== onClosing");
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
Log.e("MrXieXie---Server", "WebSocketServer ===== onClosed");
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
Log.e("MrXieXie---Server", "WebSocketServer ===== onFailure");
}
}));
try {
mockWebServer.start(InetAddress.getLocalHost(), 5223);
} catch (IOException e) {
e.printStackTrace();
}
}