I've worked before with Kryonet doing 1-to-1 communication and it worked nicely.
Now I'm doing a more 'standard' project where we'll have 1 server and several clients to connect to it.
The issue I'm having is as described in the title: client 1 connects, no problem. Then I ask for client 2 to connect and immediately client 1 disconnects. Somehow the server doesn't want to keep more than one simultaneous connection.
A couple of times we managed to have 2 connected and then whenever the 3rd connects the other drops.
Running on several different devices all ICS+ (galaxy nexus, tab2, SGS3).
The codes I'm using are very much like the examples:
server side:
server = new Server();
ServiceData.RegisterKryo(server.getKryo());
server.addListener(new MyServerListener());
try {
server.bind(ServiceData.SERVER_PORT_TCP);
server.start();
} catch (IOException e) {
Log.e(TAG, "IOException. Failed to start server. " + e.getMessage());
MyServer.this.stopSelf();
}
And then client side:
final String ip = intent.getExtras().getString(KEY_SERVER_IP);
listener = new MyClientListener();
client = new Client();
client.start();
ServiceData.RegisterKryo(client.getKryo());
client.addListener(listener);
try {
client.connect(5000, ip, ServiceData.SERVER_PORT_TCP);
} catch (IOException e) {
Log.e(TAG, "IOException. Failed to start client. " + e.getMessage() + "\n");
e.printStackTrace();
MyClient.this.stopSelf();
}
the listeners at the moment are just Log.v(TAG, "something happened); and I've also enabled all the logs from the Kryonet library with com.esotericsoftware.minlog.Log.set(com.esotericsoftware.minlog.Log.LEVEL_TRACE); so I can see when it's connecting and when it's disconnecting.
I receive two different messages upon disconnection:
DEBUG: [kryonet] Connection 3 timed out.
and
DEBUG: [kryonet] Unable to read TCP from:
really not sure what's on here and any help will be appreciated.
edit:
a bit more info:
I've realised that between INFO: [kryonet] Connection 3 connected: /192.168.0.104 and my listener receive the connected callback, it's taking around 9 seconds! Very odd.
To whom might get into the same issue.
Apparently it's an Android limitation (probably imposed because it's a mobile device)
I just moved the Server code to a normal Java application .jar and let the Android clients connect to the PC and it all works fine now. Until now tested with 6 devices connected with no problems.
Related
We are trying to create an android application for video chat using socket.io. We are using node js for the server. The server is running on a laptop. I tried to connect to the server using an Android emulator on the same laptop. But the server is not responding. I thought we shouldn't try to connect the emulator running on the same laptop where the server is running. I tried with Samsung S9+ device but the same result, the server is not responding. But interestingly when I tried to connect to the server from the Kindle device, the server is responding and printing the log. I used the same code for Emulator, S9+, and Kindle devices. Only when kindle device is trying to connect, the server is responding. Below is the code.
Android code:
String SIGNALING_URI = "http://192.168.1.101:7000"; // Laptop IP where the server is running and port 7000 where the server is listening
try {
socket = IO.socket(SIGNALING_URI);
socket.on(CREATEOFFER, new Emitter.Listener() {
#Override
public void call(Object... args) {
createOffer = true;
peerConnection.createOffer(sdpObserver, new MediaConstraints());
}
});
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Node.js (server) code:
var socketIO = require('socket.io');
var server = require('http').createServer().listen(7000, '0.0.0.0');
var io = socketIO.listen(server);
io.sockets.on('connection', function (client) {
console.log('new connection: ' + client.id);
client.on('offer', function (details) {
client.broadcast.emit('offer', details);
console.log('offer: ' + JSON.stringify(details));
});
client.on('answer', function (details) {
client.broadcast.emit('answer', details);
console.log('answer: ' + JSON.stringify(details));
});
client.on('candidate', function (details) {
client.broadcast.emit('candidate', details);
console.log('candidate: ' + JSON.stringify(details));
});
client.broadcast.emit('createoffer', {});
});
Server code should print "new connection: " log when a client is trying to connect. But it is not printing that log when Android emulator or S9+ device are trying to connect but the log is getting printed when Kindle is trying to connect. I tried to do this using web sockets instead of using socket io. The server is responding for kindle device only even using web sockets also. Can anyone please let me know if there is anything wrong in the code or do I need to change any settings on S9+ device and emulator to make it work?
Update 1:
It seems I am using socket.io-client:0.8.2 version. But on the server node js, it seems I am using socket.io 2.3.0. Does it create any problems. Where I can find compatible versions of socket io for java and node.js. Just wanted to make sure that compatibility is not causing this issue.
Update 2:
I am able to see "new connection: " on the console multiple times with different client IDs. But these logs are not generated when I was trying to connect on Emulator or S9+ device. To make sure, I tried to print socket ID on client side after IO.socket(SIGNALING_URI) by using socket.id() which is printing null on the client side.
To be clear, this question is referencing the Android SDK for SignalR...not SignalR running in a browser on an android device.
For some reason, I can not establish a connection to the server when using my wireless data network (3g). I'm able to connect to my server via web services and receive a JSON string of data, but SignalR will not connect.
SignalRFuture<Void> awaitConnection = connection.start();
try {
awaitConnection.get(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// Handle ...
} catch (ExecutionException e) {
// Handle ...
} catch (TimeoutException e) {
Log.d(TAGSR,"it timed out");
e.printStackTrace();
}
this hits the timeout exception always when I'm NOT on WiFi...even if I bump it up to a minute +. What's weird is that as soon as it times out, the other aforementioned data loads instantly. If I turn my WiFi on my phone, this connects no problem at all.
Using the same SignalR connection with my browser, I'm able to connect via 3g with no problems at all...it's only the Android SDK version that pukes unless it's on WiFi. Is there some built in mechanism to the SDK that requires a certain connection speed? If so, is there a way to override that value? My 3g ain't a ferrari, but it's fast enough to work over the web version, and work fine at that....
any ideas?
TIA
no idea why, but it appears that it's the transport selection that's causing a failure on 3g.
when I comment out one or the other (serversentevents or longpolling) in AutomaticTransport, it works fine...
private void initialize(Logger logger) {
mTransports = new ArrayList<ClientTransport>();
mTransports.add(new ServerSentEventsTransport(logger));
//mTransports.add(new LongPollingTransport(logger));
}
I've written a small file transfer program for android using standard Java sockets. The program works fine except for the following case:
I connect two android devices A and B over WiFi tethering connection. Device A is sharing the connection (enabled as wireless hotspot). When I run java server on A and client on B, the program works okay but when I run the server on device B, it can't accept any socket binding request from A. It doesn't throw any exception. Seems like the request is not reaching the server! However, both the devices are connected (ping test is okay in both directions). Can't I run socket server on a device connected as hotspot client? I thought once the networking is setup correctly, the application would work in any direction.
Also, Wireshark traces reveal nothing. What am I missing here? Please help! Here are my code snippets:
Server side (waiting for client connection):
while (true) {
try {
socket = serversocket.accept();
Runnable connectionHandler = new ConnectionHandler(
socket, fileArray, filepathNameArray,
SenderActivity.this, userID, handler);
new Thread(connectionHandler).start();
userID = userID + 1;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I would appreciate any kind of help! Thanks in advance.
I have a project that connects to a device over Bluetooth. It used to work fairly reliably, but now it fails the BluetoothSocket.connect() call every time. (Well, I got it to connect once during the thousands of attempts over a 4 hour period.) Most of the code has been taken from the standard sample chat code in the API, with the exception of the common modification in getting the BluetoothSocket device itself:
Method m = device.getClass().getMethod(
"createRfcommSocket", new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
Here's the method of interest, which gets run once a BluetoothSocket is obtained:
public void run() {
setName("ConnectThread" + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
mmSocket.connect();
} catch (Exception e) {
Log.e(TAG, "Connection to " + mmDevice.getName() + " at "
+ mmDevice.getAddress() + " failed:" + e.getMessage());
// Close the socket
try {
mmSocket.close();
} catch (Exception e2) {
Log.e(TAG, "unable to close() " + mSocketType
+ " socket during connection failure", e2);
}
connectionFailed(e.getMessage());
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
The relevant log entry (printed when the exception is caught while calling connect()) is this:
11-30 10:23:51.685: E/BluetoothChatService(2870): Connection to
ZYNO-700091 at 00:06:66:42:8E:01 failed:read failed, socket might
closed, read ret: -1
This error used to come up once in a while. I have an aggressive reconnect system - it basically hammers the connection over and over until it connects, and if it were ever to disconnect, it starts hammering it again. So, it kills the connection thread and starts from scratch constantly. I had considered that there might be an issue there - maybe a multithreading one, or maybe in handling the socket cleanup/initialization. However, if that were the case, I'd still expect the first connection attempt to succeed, since that system doesn't kick in until there's a failed connection attempt.
I looked into the source code throwing the exception. The issue seems to be that the underlying InputStream has no data. Of course, that's not really an answer, just a step towards it. Why would the stream have no data?
I'm trying to keep an open mind about the potential issue. Am I getting the BluetoothSocket properly? The fact that it was once an intermittent issue and is now nearly constant makes me suspect multithreading, but that's a relatively simple topic in Java compared to C++ - hard to screw up if you know what you're doing. Plus, the majority of this code (in particular, the parts dealing with synchronizing the threads) is straight out of the sample code.
The device on the other end is an embedded Bluetooth device, so there's not much hope of debugging the problem from that end.
UPDATE ===========================
It occurred to me that it might be due to an OS upgrade (I'm running on Galaxy Nexus phones - I have several to test with). So I unpacked a new phone with 4.0.4 and it worked! So then went back and tested on the two original test phones, both running 4.2, expecting the failure I've been seeing all this time. Strangely, now it works on those phones too. I'd like to say I did something to make this work again, but I didn't. I'm still mystified, and now also suspicious that this thing is going to work when I really need it to.
I wonder if there's a possibility that somehow connecting using 4.0.4 could have properly set the state of the server module, making it receptive to the 4.2 devices? Just a shot in the dark, I suppose...
UPDATE 2 ===========================
I've found that unpairing and re-pairing will allow the devices to connect. It's a workaround, but it's better than nothing.
Jellybean has a completely different Bluetooth stack, so version differences could certainly be triggering something, but that in itself wouldn't explain why it stays working or not-working after connecting with an older device. Could it be to do with pairing? If it happens again, try unpairing from the device and pairing again.
I know this is kind of an old question. But as I was not able to find any solution on the web, here is a workaround I recently have created: IOException: read failed, socket might closed - Bluetooth on Android 4.3
In my case it was due to bad UUID in createRfcommSocketToServiceRecord() function.
I want to connect to SPP serial profile in raspberry pi 3 and I used this UUID:
private static final UUID MY_UUID_SECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
I found somewhere in android documents' page for SPP.
I had the same problem while connecting to the arduino via bluetooth module.The problem only arised while connecting with arduino as it connected smoothly with another android phone bluetooth.
What worked for me was changing the UUID string..
I have a project that connects to a device over Bluetooth. It used to work fairly reliably, but now it fails the BluetoothSocket.connect() call every time. (Well, I got it to connect once during the thousands of attempts over a 4 hour period.) Most of the code has been taken from the standard sample chat code in the API, with the exception of the common modification in getting the BluetoothSocket device itself:
Method m = device.getClass().getMethod(
"createRfcommSocket", new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
Here's the method of interest, which gets run once a BluetoothSocket is obtained:
public void run() {
setName("ConnectThread" + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
mmSocket.connect();
} catch (Exception e) {
Log.e(TAG, "Connection to " + mmDevice.getName() + " at "
+ mmDevice.getAddress() + " failed:" + e.getMessage());
// Close the socket
try {
mmSocket.close();
} catch (Exception e2) {
Log.e(TAG, "unable to close() " + mSocketType
+ " socket during connection failure", e2);
}
connectionFailed(e.getMessage());
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
The relevant log entry (printed when the exception is caught while calling connect()) is this:
11-30 10:23:51.685: E/BluetoothChatService(2870): Connection to
ZYNO-700091 at 00:06:66:42:8E:01 failed:read failed, socket might
closed, read ret: -1
This error used to come up once in a while. I have an aggressive reconnect system - it basically hammers the connection over and over until it connects, and if it were ever to disconnect, it starts hammering it again. So, it kills the connection thread and starts from scratch constantly. I had considered that there might be an issue there - maybe a multithreading one, or maybe in handling the socket cleanup/initialization. However, if that were the case, I'd still expect the first connection attempt to succeed, since that system doesn't kick in until there's a failed connection attempt.
I looked into the source code throwing the exception. The issue seems to be that the underlying InputStream has no data. Of course, that's not really an answer, just a step towards it. Why would the stream have no data?
I'm trying to keep an open mind about the potential issue. Am I getting the BluetoothSocket properly? The fact that it was once an intermittent issue and is now nearly constant makes me suspect multithreading, but that's a relatively simple topic in Java compared to C++ - hard to screw up if you know what you're doing. Plus, the majority of this code (in particular, the parts dealing with synchronizing the threads) is straight out of the sample code.
The device on the other end is an embedded Bluetooth device, so there's not much hope of debugging the problem from that end.
UPDATE ===========================
It occurred to me that it might be due to an OS upgrade (I'm running on Galaxy Nexus phones - I have several to test with). So I unpacked a new phone with 4.0.4 and it worked! So then went back and tested on the two original test phones, both running 4.2, expecting the failure I've been seeing all this time. Strangely, now it works on those phones too. I'd like to say I did something to make this work again, but I didn't. I'm still mystified, and now also suspicious that this thing is going to work when I really need it to.
I wonder if there's a possibility that somehow connecting using 4.0.4 could have properly set the state of the server module, making it receptive to the 4.2 devices? Just a shot in the dark, I suppose...
UPDATE 2 ===========================
I've found that unpairing and re-pairing will allow the devices to connect. It's a workaround, but it's better than nothing.
Jellybean has a completely different Bluetooth stack, so version differences could certainly be triggering something, but that in itself wouldn't explain why it stays working or not-working after connecting with an older device. Could it be to do with pairing? If it happens again, try unpairing from the device and pairing again.
I know this is kind of an old question. But as I was not able to find any solution on the web, here is a workaround I recently have created: IOException: read failed, socket might closed - Bluetooth on Android 4.3
In my case it was due to bad UUID in createRfcommSocketToServiceRecord() function.
I want to connect to SPP serial profile in raspberry pi 3 and I used this UUID:
private static final UUID MY_UUID_SECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
I found somewhere in android documents' page for SPP.
I had the same problem while connecting to the arduino via bluetooth module.The problem only arised while connecting with arduino as it connected smoothly with another android phone bluetooth.
What worked for me was changing the UUID string..