Reputation: 1885
What I have: I have Android application with socket.io implementation. Servers run on node.js. Servers IPs are hardcoded in the app. Clients communicate with servers successfully - they send and receive messages.
IO.socket version I am using in my client: ('io.socket:socket.io-client:1.0.0')
What I need to get: My problem is I have to change server IP which the client is connected to, after client receives determined message.
Simplified client socket behaviour is more less like this:
socket.on("msg", new Emitter.Listener() {
@Override
public void call(Object... args) {
try {
switch (msg){
case "1":
keepOnListeningFirstServer();
break;
case "2":
connectToAnotherServer();
break;
...
What I managed to achieve is that after specific server command (msg = 2
) client connects to the second server, but client remains connected to the first server (client is still listening to commands from the first server). Actually what happens I think is that client creates second socket, but not properly closing the first socket.
In this situation, client still receives messages form first server but it sends responses to the new second server. Quite weird, but that was the furthest I managed to get with this here.
What I have tried to disconnect client and start new listener was calling on client:
socket.disconnect();
socket.close();
socket.off();
and then creating new socket and connecting it:
socket = IOSocket.getInstance(socketIP).getSocket();
socket.connect();
So my questions in general are:
Any help or advice will be very appreciated, so thanks in advance!
Upvotes: 2
Views: 10829
Reputation: 44881
You should close the socket and shutdown the channel before the disconnection really completes.
This should be your case:
//create the initial socket
Socket socket = IO.socket("your_url");
//define a constant for your channel
public static final String ON_MESSAGE_RECEIVED = "msg";
//define the event listener
private Emitter.Listener onMessageReceived = new Emitter.Listener() {
@Override
public void call(Object... args) {
//your logic for the event here
}
});
//attach your channels to the socket
socket.on(ON_MESSAGE_RECEIVED, onMessageReceived);
socket.connect();
//when you want to disconnect the socket remember to shutdown all your channels
socket.disconnect();
socket.off(ON_MESSAGE_RECEIVED, onMessageReceived);
//Then create a new socket with a new url and register again for the same event
IO.Options opts = new IO.Options();
opts.forceNew = true;
opts.reconnection = false;
socket = IO.socket("new_url", opts);
socket.on(ON_MESSAGE_RECEIVED, onMessageReceived);
socket.connect();
Upvotes: 5