Thread stucks at serversocket.accept() in android - java

I want to create communication android app using tcp server-client. I am using android phone as server and linux pc as client, I have created application on linux which works as client.When I Try to create server, it stuck at serversocket.accept(). So client is not able to connect server. I am using following code for server creation
class Thread1 implements Runnable {
int dsport = 48618
#Override
public void run() {
try {
server_socket = new ServerSocket(dsport);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = server_socket.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And I am using qt creator on client side
void run()
{
Qstring iplist;
QList<QHostAddress> ipadd = QNetworkInterface::allAddress();
socket = new QTcpSocket(this);
connect(socket,SIGNAL(connected()),this,SLOT(newConnection)));
socket->connectToHost(ipadd.at(0),48618);
}
void newConnection()
{
qDebug()<<"socket connected";
}
here ipadd.at(0) gives me local host address. Is there any issue with port I am using? if yes then how to get reliable port for server creation.
How can I resolve this issue ?

Related

How to connect react native app to java server

I've created a java server app which opens connections with serverSocket on port 3000 and it works perfectly with java client app I created. But now I started developing client app in react native and I can't understand it's socket API, because socket.io in react native forces me to use WebSocket way.
Is there any other way?
public static final int PORT = 3000;
private ServerSocket mServerSocket = null;
#Override
public void run() {
try {
mServerSocket = new ServerSocket(PORT);
} catch (IOException e) {
close();
return;
}
while (isOpen()) {
try {
mSocket = mServerSocket.accept();
ClientThread clientThread = new ClientThread(new Client(mSocket, this));
mClients.add(clientThread);
clientThread.start();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
try {
mServerSocket.close();
mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}

socket() not throwing an exception despite server not running

I have written a client to run on an android device (android 6) and when the server is up and running it connects, however when the server is down the socket() call should throw an exception however it doesn't.
I originally tried it using the NDK and ran into a very similar issue (Android NDK socket connect() returning 0 when it should fail whilst on 3g).
I am assuming this is a bug with android at this point but any insight into a solution or work around would be much appreciated.
The code in question:
public class Client implements Runnable{
private Socket socket;
private InetAddress IP;
private int port;
public Client(int port){
try {
this.IP = InetAddress.getByName(server ip);
}
catch(UnknownHostException e){
Log.d("App1", "Unknown Host, connection failed");
System.exit(1);
}
this.port = port;
Log.d("App1", "initialised");
}
#Override
public void run(){
try {
this.socket = new Socket(this.IP, this.port);
Log.d("FiX1", "Connected");
listen();
}
catch(IOException e){
Log.d("FiX1,","connection failed");
System.exit(1);
}
finally
{
try{
socket.close(); // dispose
}
catch(IOException e){
System.exit(1);
}
}
}
public void listen() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String cominginText = "";
try {
cominginText = in.readLine();
Log.d("FiX1",cominginText);
} catch (IOException e) {
//error ("System: " + "Connection to server lost!");
System.exit(1);
break;
}
}
} catch (IOException e) {
System.exit(1);
}
}
}
The best solution I could find was to manually send an acknowledgement from the server that a connection had been made, the client would retry the connection if it did not receive this message within a certain time after it claimed to have connected.
There is a difference between a TCP connection "close" vs "disconnect".
If you close the socket connection from server using socket.close() then you will get exception in client side, if you try to read from that connection or vice versa.
However, if one side just disappears(shut down the program) then the other side has no way of knowing that. So the other side will wait for response for read call.
The TCP protocol was designed to be reliable in hostile communication environments and it will not normally decide a connection is closed just because it has not heard from the other side for a while.

How to create a socket that listens a localhost port in Android

Before explain my doubt I want to mension that there're three "actors" in this enviorement:
A desktop program executed in some server
A person who uses this program remotely through a computer
And an Android tablet application that is connected with the computer via USB
When the person clicks on a link bar in this program that he is using remotely there's a shell script that sends a string to the person's computer port(e.g 1100). The requirement is: After recive this string from the desktop send it to the tablet.
So, what is the best way to recive this string from the desktop to the tablet?
Now there's a java daemon that is running in the desktop computer who is listening the 1100 port. This java app is working as a intermidiate between the desktop computer and the tablet, but I think that maybe there's a way to delete this daemon and just using the tablet to recive the computer data creating a socket.
You can also implement Java Sockets in Android. Like wise on Desktop Sockets in Android listens on ports but this will be accessed locally as there is no such way to assign static usable IP to an Android device.
There is another solution which is socket.io
Socket.io is one of the best socket library i have ever used. Implement socket.io on Node.js server and on Android simply connect to Node.js server and you can send same string to all connected users whether it is a Desktop or Android.
private class ServerThread extends Thread {
#Override
public void run() {
try {
serverSocket = new ServerSocket(portNumber);
while (true) {
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
LOGGER.error("Error on accept!");
}
// new thread for a client
new EchoThread(clientSocket).start();
}
}catch (Exception e) {
e.printStackTrace();
}
finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public class EchoThread extends Thread {
protected Socket clientSocket;
BufferedReader br = null;
public EchoThread(Socket clientSocket) {
this.clientSocket = clientSocket;
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
...
}
isConnected = true;
while (isConnected) {
try {
receivedMessage = br.readLine();
if (!Strings.isNullOrEmpty(receivedMessage)) {
....
}
else {
//sleep 0,1s
//TODO (ver): Thread.sleep(100);
}
} catch (Exception e) {
if (e instanceof IOException) {
}
else if (e instanceof JsonSyntaxException){
}
else {
try {
Thread.sleep(2000);
} catch (InterruptedException inte) {
inte.printStackTrace();
}
}
}
if (//yourmessagecondition){
isConnected = false;
}
}
if (!isConnected){
try {
br.close();
clientSocket.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
}
}
Hope this helps, it is working here... You probably find easier/simple examples on the Internet.
PS: If you are using a USB cable to communicate with the computer app, you can use the "adb forward" command, just google for some examples and accept this answer if it helped ;)

Server hangs when client disconnects

i am creating a multiple-client/server app whenever any client disconnects from
my server it just hangs.
how can i set any condition that will tell me print some message whenever
any client disconnects from the server
here is my server code
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
System.out.println("server starting.......");
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
System.out.println("Ready to accept.......");
socket = serverSocket.accept();
System.out.println(" client Connected with ip address =" +socket.getRemoteSocketAddress().toString());
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
System.out.println("catch block");
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
any help will be appreciated
It's not clear whether you mean disconnect because the conversation was over (ie: everything completed successfully) or the disconnect is because of some network problems (or the client canceled the request).
If it's the first case, then it's easy: the protocol you are using (your own, or http, or whatever) is in charge of defining how to determine that a conversation was over. If that situation arises, then you just close the socket.
If it's the second case, then you'd have to have an algorithm in place to determine whether or not the connection must be closed. For instance, by implementing a timeout, or a slow-read threshold. Take a look at the Socket's javadoc for instructions on how to set a timeout.
It's also worth noting that it's fine to create your own servers when you want to practice or learn something, but you'd be better off using an existing solution, like vert.x or a slimmed down version of Wildfly, for instance. The overhead of such servers is very low, nowadays, while still providing very robust networking capabilities.

Bluetooth Server Android - Client Java Bluecove. UUID?

I'm writing an application to communicate between my smartphone and a computer using a bluetooth device.
I'm using Bluecove to manage the bluetooth on the computer, and the android API for my android device.
However, when I'm debugging, nothing happens. I think that the problem is that the UUID is wrong. I'm not sure how to get the devices to identify each other, in order to establish a connection.
I have read some other "questions" about those tags, but what I've tried didn't fix my problem:
Simple Bluetooth data receiver Android
Android: obtaining uuid of a bluetooth device
Etc...
Here's what I've written so far:
For tho android (Server) (This is the function that will make the connection)
public void connectSocket(){
blueAdapter.cancelDiscovery(); // Cancel discovery because it'll slow down the connection
final BluetoothServerSocket serverSocket;
BluetoothServerSocket sSocket= null;
try{
sSocket = blueAdapter.listenUsingRfcommWithServiceRecord("BluetoothJANE", MY_UUID);
}catch(IOException e){}
serverSocket = sSocket;
Thread acceptThread = new Thread(new Runnable() {
#Override
public void run() {
BluetoothSocket socket = null;
while(true){
try{
socket = serverSocket.accept();
}catch(IOException e){
break;
}
if(socket != null){
try{
iStream = socket.getInputStream();
oStream = socket.getOutputStream();
} catch(IOException e){}
}
}
}
});
acceptThread.start();
}
For java app on PC (This is the constructor of the class (it's on an independent thread) that will manage the bluetooth connection)
public ModuleBluetooth() {
StreamConnectionNotifier notifier = null;
StreamConnection connection = null;
try {
blueDevice = LocalDevice.getLocalDevice();
blueDevice.setDiscoverable(DiscoveryAgent.GIAC);
String url = "btspp://localhost:" + MY_UUID.toString()
+ ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (BluetoothStateException e) {
System.out
.println("ModuleBluetooth: Error getting the bluetooth device");
} catch (IOException e) {
}
System.out.println("waiting for connection...");
try {
connection = notifier.acceptAndOpen();
System.out.println("Conenction created");
} catch (IOException e) {
System.out.println("Can not create the connection");
}
}
Could somebody please help me? Any thoughts would be very much appreciated.
I have also tried to use some functions to acquire the UUID (in android) such as, [fetchUuidsWithSdp][2] (and the related functions) but eclipse doesn't recognize that functions (It seems that they don't exist in "my" API).
http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#fetchUuidsWithSdp%28%29
Try this example, http://luugiathuy.com/2011/02/android-java-bluetooth/ . I also had problem related to UUID, in this example, Converting UUID to 00001101-0000-1000-8000-00805F9B34FB worked out of the box. See this link: http://www.avetana-gmbh.de/avetana-gmbh/produkte/doc/javax/bluetooth/UUID.html

Categories