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 😋
Related
i am implementing SignalR on client side with android using kotlin. I can connect and can get connection id its mean connection established succeeded after that invoke and subscribed it, when i call hubConnection.on() it could not move inside any log or nor catch any exception. where i have done mistake any help is appreciated
lifecycle.coroutineScope.launchWhenCreated {
hubConnection =
HubConnectionBuilder.create("baseurl",)
.build()
hubConnection.start().blockingAwait()
Log.e("123**** ", "Established connection......" + hubConnection.connectionId)
val userID = "Model.user_id"
try {
hubConnection.invoke(
"Subscribe",
hubConnection.connectionId,
arrayListOf(
userID,
"$userID+_messaging",
"$userID+_notification",
"$userID+_setting",
"$userID+_plan",
"$userID+_refresh"
)
).subscribe()
} catch (e: Exception) {
Log.e("ExceptionDone: ", e.toString())
}
try {
hubConnection.on("ReceiveSimplifiedRealTime", { response: String ->
// runOnUiThread {
Log.e("Receive123**** ", response)
//}
}, String::class.java)
} catch (e: Exception) {
Log.e("Receive123**** ", e.toString())
} catch (e: ExecutionException) {
Log.e("Receive123**** ", e.toString())
}
}
this is my first time creating a chat using socket in Android app. I have a nodejs back-end. I also a have a front-end app written with Reactjs and it's working as expected. However, it's not the case for my Android app. Please see below code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chatroom)
send.setOnClickListener(this)
leave.setOnClickListener(this)
// Get the nickname and roomName from entrance activity.
try {
userName = intent.getStringExtra("username")!!
roomName = intent.getStringExtra("room")!!
} catch (e: Exception) {
e.printStackTrace()
}
// Set ChatRoom RecyclerView adapter
chatRoomAdapter = ChatRoomAdapter(this, chatList)
recyclerView.adapter = chatRoomAdapter
val layoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = layoutManager
// Let's connect to our Chat room! :D
try {
val opts = IO.Options()
opts.forceNew = true;
opts.reconnection = false
opts.transports = arrayOf(Polling.NAME, PollingXHR.NAME, WebSocket.NAME)
// This address is the way you can connect to localhost with AVD (Android Virtual Device)
mSocket = IO.socket(URL, opts)
Log.d(TAG, "Name $URL")
Log.d(TAG, "Opts $opts")
} catch (e: Exception) {
e.printStackTrace()
Log.d("Fail", "" + "Failed to connect")
}
mSocket.connect()
mSocket.on(Socket.EVENT_CONNECT, Emitter.Listener {
val data = initialData(userName, roomName)
val jsonData = gson.toJson(data) // Gson changes data object to Json type.
Log.d(TAG, "json >> $jsonData")
Handler(Looper.getMainLooper()).postDelayed(object : Runnable {
override fun run() {
mSocket.emit("join", jsonData)
}
},200)
Log.d("Success", "" + mSocket.id())
mSocket.on("message", onUpdateChat)
});
mSocket.on(Socket.EVENT_CONNECT_ERROR, Emitter.Listener { args ->
Log.e(TAG, "Andito na ba ko? ${args[0]} size: ${args.size}")
});
mSocket.on(Socket.EVENT_ERROR, Emitter.Listener {
Log.e(TAG, "Error")
});
}
But I keep getting io.socket.engineio.client.EngineIOException: server error
Anyone encountered this error? I would gladly appreciate any kind of help. Thanks.
I've been trying to use khttp to send an .jpg file in an android activity but haven't been able to make it work.
fun sendImage(view: View) {
try {
var bmp = (imageView?.drawable as BitmapDrawable).bitmap
var bos = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.JPEG, 0, bos)
var response: Response? = null
findViewById<TextView>(R.id.image_desc).text = "Connecting to " + SERVER_URL;
try {
val job=GlobalScope.launch {
response = post(SERVER_URL, files = listOf(File(path).fileLike(name = "Image.jpg")))
}
findViewById<TextView>(R.id.image_desc).text = "Image contains: ${response?.text}"
} catch (e: Exception) {
findViewById<TextView>(R.id.image_desc).text = "Connection failed - please check fields are valid"
findViewById<TextView>(R.id.image_desc).text = e.toString()
}
} catch (e: UnknownHostException) {
findViewById<TextView>(R.id.image_desc).text = "Unknown host :("
e.printStackTrace()
} catch (e: IOException) {
findViewById<TextView>(R.id.image_desc).text = "IO exceptiion :("
e.printStackTrace()
} catch (e: Exception) {
findViewById<TextView>(R.id.image_desc).text = "Other exception :("
e.printStackTrace()
}
}
As soon as i send the image, image_desc textView's text change to Image contains: null. I'm sure the server isn't the problem, since when I test it with this python code:
import requests
url=...
files = {'file': open('./test/cat.jpg', 'rb')}
r=requests.post(url,files=files)
print (r.text)
I get the desired response after a short delay. I've tried turning sendImage to a suspend func and writing job.join() but that crashes the app. How should fix this?
Try next code:
val job = GlobalScope.launch(Dispatchers.Main) {
val postOperation = async(Dispatchers.IO) { // <- extension on launch scope, launched in IO dispatcher
// blocking I/O operation
post(SERVER_URL, files = listOf(File(path).fileLike(name = "Image.jpg")))
}
response = postOperation.await() // wait for result of I/O operation without blocking the main thread
findViewById<TextView>(R.id.image_desc).text = "Image contains: ${response?.text}"
}
Also add next line to app's build.gradle dependency:
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1'
Note that GlobalScope is discouraged to use, to launch a coroutine use an instance of CoroutineScope, or existing instance like viewModelScope or lifecycleScope.
UPDATE:
The correct approach would be to use lifecycleScope in Activity:
lifecycleScope.launch { // uses Dispatchers.Main context
val response = withContext(Dispatchers.IO) { // change context to background thread
// blocking I/O operation
post(SERVER_URL, files = listOf(File(path).fileLike(name = "Image.jpg")))
}
findViewById<TextView>(R.id.image_desc).text = "Image contains: ${response?.text}"
}
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)
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.