Android TCP client trying to connect to server - android

I am trying to make a TCP client that will try to connect to a server. If the server cannot be reached then it must retry after a fixed time. If the connection is lost then it should try to re-connect again. When connected it should be able to read data from the server (ASCII strings). This piece of code is not working as intended [App crashing without a server].
How can I fix it? (Note: Server is extremely unreliable and cannot expect gracefully disconnect)
package com.thinkalvb.sensorstorm
import android.util.Log
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.Socket
import java.net.SocketException
private const val TAG = "Storm_Commander"
class Commander : Runnable {
private lateinit var mTcpSocket: Socket
override fun run() {
val serverAddress = MainActivity.serverAddress
val serverPort = MainActivity.portNumber
while(!Thread.currentThread().isInterrupted) {
try {
Log.d(TAG,"Waiting for Server")
mTcpSocket = Socket(serverAddress, serverPort)
mTcpSocket.soTimeout = 5000
mTcpSocket.keepAlive = true
val receiveBuffer = BufferedReader(InputStreamReader(mTcpSocket.getInputStream(), "UTF-8"))
Log.d(TAG,"Connected to Server")
while (true) {
val command = receiveBuffer.readLine()
if (command != null) {
Log.d(TAG, command)
}
}
} catch (e: SocketException) {
Log.e(TAG, "Socket Error:", e)
} catch (e: IOException) {
Log.e(TAG, "IO Error:", e)
} finally {
mTcpSocket.close()
Log.d(TAG,"Client socket closed")
}
}
}
}
The entire project is in Github https://github.com/ThinkalVB/SensorStorm
Errors:
2021-03-25 21:05:44.201 1865-1865/com.thinkalvb.sensorstorm D/Storm_Location: Location Service created
2021-03-25 21:05:44.204 1865-1865/com.thinkalvb.sensorstorm D/Storm_Acceleration: Acceleration Sensor created
2021-03-25 21:05:44.204 1865-1865/com.thinkalvb.sensorstorm D/Storm_Orientation: Orientation Sensor created
2021-03-25 21:05:44.290 1865-1865/com.thinkalvb.sensorstorm D/Storm_Camera: Camera Service created
2021-03-25 21:05:44.290 1865-1865/com.thinkalvb.sensorstorm D/Storm_Temperature: Temperature Sensor created
2021-03-25 21:05:44.292 1865-1865/com.thinkalvb.sensorstorm D/Storm_MainActivity: Main Activity created
2021-03-25 21:05:48.986 1865-1865/com.thinkalvb.sensorstorm D/Storm_MainActivity: Service starting
2021-03-25 21:05:48.987 1865-1957/com.thinkalvb.sensorstorm D/Storm_Commander: Waiting for Server
2021-03-25 21:07:56.396 1865-1957/com.thinkalvb.sensorstorm E/Storm_Commander: Socket Error:
java.net.ConnectException: failed to connect to /10.0.2.2 (port 1357) from /:: (port 37528): connect failed: ETIMEDOUT (Connection timed out)
at libcore.io.IoBridge.connect(IoBridge.java:137)
at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:137)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
at java.net.Socket.connect(Socket.java:570)
at java.net.Socket.<init>(Socket.java:450)
at java.net.Socket.<init>(Socket.java:250)
at com.thinkalvb.sensorstorm.Commander.run(Commander.kt:20)
at java.lang.Thread.run(Thread.java:764)
Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
at libcore.io.Linux.connect(Native Method)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:118)
at libcore.io.IoBridge.connectErrno(IoBridge.java:151)
at libcore.io.IoBridge.connect(IoBridge.java:129)
at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:137) 
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390) 
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230) 
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212) 
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436) 
at java.net.Socket.connect(Socket.java:621) 
at java.net.Socket.connect(Socket.java:570) 
at java.net.Socket.<init>(Socket.java:450) 
at java.net.Socket.<init>(Socket.java:250) 
at com.thinkalvb.sensorstorm.Commander.run(Commander.kt:20) 
at java.lang.Thread.run(Thread.java:764) 
2021-03-25 21:07:56.405 1865-1865/com.thinkalvb.sensorstorm D/Storm_MainActivity: Service stopping

A temporary solution for those looking for some code to start with.
while(!Thread.currentThread().isInterrupted) {
try {
Log.d(TAG, "Waiting for Server")
mTcpSocket = Socket()
mTcpSocket.connect(serverSocketAddress, 10000)
mTcpSocket.keepAlive = true
mTcpSocket.soTimeout = 15000
if(mTcpSocket.isConnected){
mTCPBufferIncoming = BufferedReader(InputStreamReader(mTcpSocket.getInputStream(), "UTF-8"))
Log.d(TAG, "Connected to Server")
processCommands()
}
mTcpSocket.close()
} catch (e: SocketException) {
Log.e(TAG, "Socket Error:", e)
} catch (e: IOException) {
Log.e(TAG, "IO Error:", e)
} catch (e: Exception) {
Log.e(TAG, "Exception:", e)
}
}
private fun processCommands()
{
var command: String
while (mTCPBufferIncoming.readLine().also { command = it } != null) {
Log.d(TAG, command)
}
}

Related

FTPClient.connect's parameter

I'm trying to connect ftp server with FTPClient.
but connect is not working.
I passed ip address and port number as parameters.
When i don't write port number, "Socket:failed to connect to /106.10.40.222 (port 21) from /:: (port 37510): connect failed: ECONNREFUSED (Connection refused)" is occuring.
Ip address is "106.10.40.222" and port is 1028.
I will do download file in stp server after connecting.
fun ftpFileDownload(
uri: String?,
id: String?,
pw: String?,
localFile: String?,
ftpFile: String?,
directoryLocation: String?
) {
var ftp: FTPClient? = null
try {
ftp = FTPClient()
ftp.setControlEncoding("UTF-8")
ftp.connect(uri, 1028) //uri = "106.10.40.222"
} catch (e: SocketException) {
Log.d("kkang", "Socket:" + e.message)
} catch (e: IOException) {
Log.d("kkang", "IO:" + e.message)
} finally {
if (ftp != null && ftp.isConnected()) {
try {
ftp.disconnect()
} catch (e: IOException) {
}
}
}
}
I want to know how to connect in FTPClient

Cannot connect to socket.io in android , saying invalid namespace

When i try to connect my android app with socket.io, it saying invalid namespace. There is no issue with socket url , but having problem in connection, please help if you faced this issue ever. Thanks!
val options = io.socket.client.IO.Options().apply {
forceNew = false
reconnection = true
}
private val socket: Socket = io.socket.client.IO.socket(socket_url,options)
val socket = applicationAccessorImpl.socket
socket.connect()
socket.once(Socket.EVENT_CONNECT) {
try {
Log.d(TAG, "connect")
} catch (e: Exception) {
Log.d(TAG, e.message!!)
}
}.on(Socket.EVENT_CONNECT_ERROR) {
val e = it[0]
Log.e(TAG, "error $e")
}.on(Socket.EVENT_DISCONNECT) {
val e = it[0]
Log.e(TAG, "Transport error $e")
}
Sorry , it was my mistake , i was passing the wrong url 😋

MQTT broker not connecting after internet disconnect and reconnect in Android 10

In my application i connect to IOT Device at that internet got disconnect and connection with MQTT Broker also disconnect then i send wifi to my IOT Device through TCP client and closing the socket i reconnect my internet connection after internet is connected again when i hit to re-establish connection with MQTT broker i got this ERROR:
MqttException (0) - java.net.SocketException: socket failed: ENONET (Machine is not on the network)
private fun initMQTTConnector() {
clientID = Installation.id(context)
client = MqttAndroidClient(
context, String.format(
"%s:%s",
BuildConfig.mqtt_server_url,
BuildConfig.mqtt_server_port
),
clientID, MemoryPersistence()
)
client!!.setCallback(listener)
Timber.e(
"qq - " + String.format(
"%s:%s",
BuildConfig.mqtt_server_url, //"tcp://192.168.1.164"
BuildConfig.mqtt_server_port
) + " -- " + clientID
)
connectToMQTTServer()
}
fun connectToMQTTServer() {
try {
if(client == null){
Timber.e("qq - client")
initMQTTConnector()
}else{
Timber.e("qq - Retrying the MQTT connection...!")
val options = MqttConnectOptions()
options.setCleanSession(false) // change for mqtt connection issue
options.setAutomaticReconnect(true)
options.userName = BuildConfig.mqtt_server_user_name
options.password = BuildConfig.mqtt_server_password.toCharArray()
options.setKeepAliveInterval(90) //seconds
token = client!!.connect(options)
eventBusManager?.post(
EventBusManager.MessageEvent(
EventBusConstants.MQTT_CONNECTING
)
)
token?.actionCallback = object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken) {
// We are connected
Timber.e("qq - onSuccess for connection :: token.actionCallback")
// Timber.d("onSuccess for connection")
eventBusManager?.post(
EventBusManager.MessageEvent(
EventBusConstants.MQTT_CONNECTED
)
)
subscribeToReportedTopic()
subscribeToLoadedDevicesReportedChannel()
}
override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable?) {
// Something went wrong e.g. connection timeout or firewall problems
Timber.e("qq - onFailure for connection :: token.actionCallback - " + exception.toString())
eventBusManager?.post(
EventBusManager.MessageEvent(
EventBusConstants.MQTT_NOT_CONNECTED
)
)
exception?.printStackTrace()
// connectToMQTTServer()
}
}
}
} catch (e: Exception) {
eventBusManager?.post(
EventBusManager.MessageEvent(
EventBusConstants.MQTT_NOT_CONNECTED
)
)
Timber.e("qq - Error occurred while connecting MQTT Client, Error = " + e.toString())
e.printStackTrace()
}
}

Not able to connect with bluetooth device with socket in android studio

Hello everyone I am new to android development i am connecting with bluetooth device as a client in different class thread. If Nullpointerexcception occur then i use default UUID. After this when i use socket.connect() it show debug warning and don't send any pair request to device. Nothing happen. I am new to android development if any one can help. Thank you in advance.
Warning and Logs
here is my code in Thread;
class ConnectWithDevice(context : ConnectWithBluetooth, device : BluetoothDevice) : Thread(){
private val mContext : ConnectWithBluetooth = context
private val mmSocket : BluetoothSocket
private val mmDevice : BluetoothDevice
// Default UUID
private val mmDefaultUUID = UUID.fromString("78c374fd-f84d-4a9e-aa5b-9b0b6292952e")
init {
var temp : BluetoothSocket? = null
mmDevice = device
try {
temp = device.createRfcommSocketToServiceRecord(mmDevice.uuids[0].uuid)
}catch (en : NullPointerException){
en.printStackTrace()
temp = device.createRfcommSocketToServiceRecord(mmDefaultUUID)
}catch (e : IOException){
e.printStackTrace()
Log.e("TAG","Socket's create() method failed",e)
}
mmSocket = temp!!
Log.i("TAG","Got the Socket")
}
override fun run() {
// Cancel discovery because it otherwise slows down the connection.
if(mContext.bluetoothAdapter != null){
mContext.bluetoothAdapter!!.cancelDiscovery()
}
try{
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
Log.i("TAG","Connecting...")
mmSocket.connect()
Log.i("TAG","Bluetooth Successfully Connected")
}catch (connectException : IOException){
// Unable to connect; close the socket and return.
try{
mmSocket.close()
}catch (closeException : IOException){
Log.e("TAG","Could not close the client socket",closeException)
}
return
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
Log.i("TAG","Device is Connected")
//manageMyConnectedSocket(mmSocket)
}
// Closes the client socket and causes the thread to finish.
// Call this method from the main activity to shut down the connection.
fun cancel(){
try {
mmSocket.close()
} catch (e: IOException) {
Log.e(ContentValues.TAG, "Could not close the client socket", e)
}
}
}
Finally i find the solution here it is ->
I use this code ->
val m = device.javaClass.getMethod("createRfcommSocket", *arrayOf<Class<*>>(Int::class.java))
temp = m.invoke(device, 1) as BluetoothSocket
Instead of this ->
temp = device.createRfcommSocketToServiceRecord(mmDevice.uuids[0].uuid)

Bluetooth client Socket get same exception everytime

I am writing an Android app mostly in Kotlin that is supposed to scan for Bluetooth devices and also pair with them. I also want it to have a Bluetooth server socket running in the background to await connection attempts. However, I keep running into the same exception when attempting to invoke the BluetoothSocket.connect() method. The exception is:
10-10 20:07:57.917 18643-27894/com.example.zemcd.toofxchange E/Pairing Thread: error connecting
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:754)
at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:766)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:388)
at com.example.zemcd.toofxchange.PairingThread.run(BluetoothUtils.kt:83)
I read that this could be fixed with code similar to
btSocket = device.javaClass.getMethod("createRFcommSocket", Int::class).invoke(device, 1) as BluetoothSocket
But this does not work. It causes the app to crash with a ReflectException caused by NoSuchMethod. Also I have read that this is not a published method for a reason and I would like to try to use the published createRFcommSocketToServiceRecord() method. I am unsure of where to go from here, or what exactly is causing the IOException. Also, I never even get to the pairing screen. I am trying to find what is the cause of this exception, and how to fix it. My code:
class BluetoothUtils {
companion object {
val _UUID = UUID.fromString("a0e7e4c7-0e4e-43b7-9d18-659192512164")
val TAG = "BluetoothUtils"
fun initPairingServer(adapter: BluetoothAdapter){
var mmServerSocket: BluetoothServerSocket? = null
try {
var tmp = adapter.listenUsingRfcommWithServiceRecord(TAG, _UUID)
mmServerSocket = tmp
ListenThread(mmServerSocket).start()
}catch (ioe: IOException){
Log.e(TAG, "Error initializing Bluetooth", ioe)
}
}
fun pair(adapter: BluetoothAdapter, device: BluetoothDevice){
var btSocket: BluetoothSocket? = null
try {
adapter.cancelDiscovery()
btSocket = device.createRfcommSocketToServiceRecord(_UUID)
PairingThread(btSocket).start()
}catch (ioe: IOException){
Log.e(TAG, "error connecting", ioe)
}
}
}
}
class ListenThread(val btServSock: BluetoothServerSocket) : Thread(){
companion object {
val TAG = "ListenThread"
}
var btSocket: BluetoothSocket? = null
override fun run() {
super.run()
while (true){
try {
Log.d(TAG, "listening . . . ")
btSocket = btServSock.accept()
}catch (ioe: IOException){
Log.e(TAG, "Error", ioe)
break
}
//manage connection here
//with either BluetoothUtils function
//or BluetoothSocket extension
}
}
}
class PairingThread(val btSocket: BluetoothSocket) : Thread(){
companion object {
val TAG = "Pairing Thread"
}
override fun run() {
super.run()
try {
Log.d(TAG, "attempting to connect")
btSocket.connect()
}catch (ioe: IOException){
Log.e(TAG, "error connecting", ioe)
btSocket.close()
}
}
}
Please somebody help me find my problem. Could it be that I'm attempting to connect to a device that isn't using the same UUID? I am just trying to connect to my laptop.

Categories

Resources