我想在Android客户端和Nodejs服务器之间建立持久连接。我选择在后台运行的intentservice中启动连接,并通过send方法与服务器进行交互。 连接稳定并且send方法起作用,但是从不调用WebSocketClient方法(onOpen,onMessage,onClose,onError)。
我们正在使用
implementation 'org.java-websocket:Java-WebSocket:1.3.0'
客户:
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
public class WebSocketService extends IntentService {
public static WebSocketClient webSocketClient;
private URI uri;
public WebSocketService() {
super("WebSocketService");
try {
uri = new URI("ws://192.168.43.54:1337");
} catch (URISyntaxException e) {
e.printStackTrace();
}
webSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake handshakedata) {
//some code
}
@Override
public void onMessage(String message) {
}
@Override
public void onClose(int code, String reason, boolean remote) {
}
@Override
public void onError(Exception ex) {
}
};
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
webSocketClient.connect();
return super.onStartCommand(intent,flags,startId);
}
@Override
protected void onHandleIntent(final Intent intent) {
Handler handler = new Handler(getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
//handle intent
}
});
}
}
MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, WebSocketService.class);
startService(intent);
}
服务器Nodejs:
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
// process HTTP request. Since we're writing just WebSockets
// server we don't have to implement anything.
response.end("WORK!!");
});
server.listen(1337, function() {console.log("SERVER STARTED"); });
// create the server
wsServer = new WebSocketServer({
httpServer: server
});
// WebSocket server
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
console.log("A connection started");
connection.on('message', function(message) {
if (message.type === 'utf8') {
// process WebSocket message
connection.sendUTF(message.utf8Data);
console.log("MESSAGE RECEIVED:" +message.utf8Data);
}
});
connection.on('close', function(connection) {
// close user connection
console.log("A connection is closed");
});
});