Multicast Socket Android Error On Data Recieving? - android

I am new in socket programming. i am using Multicast socket for broadcasting through wifi hotspot network.But i am facing problem at the reciver side.
Here is my code
Server Side
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class SenderService extends Service
{
SenderThread currentSender;
public class SenderThread extends Thread
{
public void run()
{
Log.d("in thread","in service");
try
{
InetAddress group = InetAddress.getByName("224.0.0.3");
int port=10000;
DatagramSocket sock=new DatagramSocket();
sock.setBroadcast(true);
String msg="hello";
byte []b3=new byte[1024];
DatagramPacket packet;
b3=msg.getBytes();
while (true)
{
try
{
packet = new DatagramPacket(b3, b3.length,group, port);
sock.send(packet);
Log.d("MSG:", "sent");
} catch (IOException e)
{
Log.d("Send Excp:", e+"");
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
sock.close();
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
new SenderThread().start();
return Service.START_STICKY;
}
}
Client Side Code
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.util.Enumeration;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ReceiverActivity extends Activity
{
Button b;
Handler h;
class MyRTh extends Thread
{
InetAddress group=null ;
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
MulticastLock lock = wifi.createMulticastLock("HelloAndroid");
public void run()
{
try
{
lock.acquire();
}
catch (Exception e) {
// TODO: handle exception
Log.d("lock",e+"");
}
try
{
final MulticastSocket sock=new MulticastSocket(10000);
group= InetAddress.getByName("224.0.0.3");
//sock.setSoTimeout(15000);
try
{
sock.joinGroup(group);
}
catch(Exception e)
{
Log.d("join",""+e.toString());
}
while(true)
{
try
{
Log.d("in try","l4");
byte[] data = new byte[1024];
// TODO Auto-generated method stub
DatagramPacket packet = new DatagramPacket(data, data.length);
Log.d("in run","l4");
try {
sock.receive(packet);
String s = new String(packet.getData());
Log.e("MSG:", "Received");
Log.d("msg",s);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("err",e.toString());
}
}
catch (Exception e)
{
Log.d("Excp", e.toString()+"");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}catch (Exception e) {
// TODO: handle exception
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receiver);
Toast.makeText(getApplicationContext(), "Receiving", Toast.LENGTH_SHORT).show();
Log.d("1","l1");
b=(Button)findViewById(R.id.buttonr);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0)
{
MyRTh th=new MyRTh();
th.start();
}
});
}
}
My problem is my client side code stuck when it goes to socket.receive() method. I started my mobile data at both sides. Started Hotspot at server side and connected to it from client.

My problem is my client side code stuck when it goes to socket.receive() method
It blocks.
InetAddress group = InetAddress.getByName("224.0.0.3");
The problem is here. Multicast addresses in the range 224.0.0.0 to 224.0.0.255 are reserved for low-level multicast support operations. Use an address in the range 224.0.1.0 to 239.255.255.255, but see also RFC 2365.
sock.setBroadcast(true);
Unnecessary. Remove. You aren't broadcasting, you are multicasting.
byte []b3=new byte[1024];
DatagramPacket packet;
b3=msg.getBytes();
You don't need to initialize b3 when you reassign it two lines later.
finally
{
sock.close();
}
You are closing the socket inside the while (true) loop. So it will send one multicast and then exit with a 'socket closed' exception, which you haven't reported here. Remove.
String s = new String(packet.getData());
That should be new String(packet.getData(), packet.getOffset(), packet.getLength().

try to set able this enable socket.setBroadcast(true);
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.setBroadcast(true);
socket.receive(packet);

Related

Never ending service that hears to incoming data though a port from some IP address for UDP data

I am building an application that connects with a server which is my Raspberry pi.
My android application sends data to the server and gets the response for the sent command.
Raspberry pi can generate interrupts at any time and will send it to the android application. I want to create a service that should never die and should always keep on listening to the interrupts sent by raspberry pie.
package com.example.test;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketException;
import java.util.Timer;
import java.util.TimerTask;
/**
* This is a service that will never stop and will again restart if it gets killed
*/
public class WifiUnstoppableService extends Service{
private static final String TAG = WifiUnstoppableService.class.getSimpleName();
private Timer mTimer = null;
private String result = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(timerTask, 2000, 2 * 2000);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
} catch (Exception e) {
e.printStackTrace();
}
Thread thread = new Thread(){
#Override
public void run() {
while (true){
try {
DatagramSocket socket = new DatagramSocket(null);
InetSocketAddress address = new InetSocketAddress("192.168.42.1", 5001);
socket.bind(address);
try {
byte[] receiveData = new byte[2048];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String receivedPacket = new String(receivePacket.getData());
Log.d(TAG, receivedPacket);
socket.close();
}catch (NumberFormatException e){
e.printStackTrace();
}
}catch (SocketException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
};
thread.start();
return super.onStartCommand(intent, flags, startId);
}
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
}
};
#Override
public void onDestroy() {
super.onDestroy();
try {
mTimer.cancel();
timerTask.cancel();
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent("com.test.interruptReceiver");
sendBroadcast(intent);
}
}
But this is not working.
Can anyone help me with what am I doing wrong.
Practically you should not create a never ending service because if you create one, it will not work properly due to doze mode. And more thing, in Android O you are strictly not allowed to run a service for a unlimited time in background.

Android socket.io Service stop

how can i keep the socket active on the service, when i close the app it disconnected, from node, i call it from the main activity, with startService(new Intent(this, sys_service.class)); the socket its fine while the app its active
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
public class sys_service extends Service {
Socket mSocket;
TelephonyManager manager;
JSONObject chat_response;
private Handler mHandler = new Handler();
String msg_over;
{
try {
mSocket = IO.socket("http://xxxx:8001");
} catch (URISyntaxException e) {
Toast.makeText(this, "refused", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Toast.makeText(this,"Service Active :)", Toast.LENGTH_LONG ).show();
run_app();
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service stop :)", Toast.LENGTH_LONG ).show();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent){
run_app();
return null;
}
public Socket getSocket() {
return mSocket;
}
public void run_app() {
mSocket.connect();
manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
final JSONObject uidJson = new JSONObject();
String real = manager.getDeviceId();
try {
uidJson.put("uid", real);
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.on("connect", new Emitter.Listener() {
public void call(Object... args) {
mSocket.emit("uid", uidJson);
}
});
mSocket.on("chat", new Emitter.Listener() {
public void call(Object... args) {
String chat_msg = args[0].toString();
try {
chat_response = new JSONObject(chat_msg);
} catch (JSONException e) {
e.printStackTrace();
}
msg_over = chat_response.optString("msg");
final JSONObject chat = new JSONObject();
try {
chat.put("msg", "all fine");
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("test", msg_over);
//Toast.makeText(StartActivity.this, msg, Toast.LENGTH_SHORT).show(); Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
Log.d("chat", msg_over);
}
});
}
}

Android do in background

package com.example.handy;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.Scanner;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText ipaddress;
private Button connect;
private Button wipe;
private static String myIp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText) findViewById(R.id.ipaddress_felid);
connect = (Button) findViewById(R.id.connect);
wipe =(Button) findViewById(R.id.wipe);
//Button press event listener
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setMyIp(ipaddress.getText().toString());
// myComs.sending_data(getMyIp() , "Got connected");
try
{
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
new Incomingdata(s).execute();
OutputStream o = s.getOutputStream();
PrintWriter p = new PrintWriter(o);
p.println("You are connected");
p.flush();
readContacts();
readSms();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
wipe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String kill = "5";
myComs.sending_data(MainActivity.getMyIp(), kill);
finish();
}
});
}
public class Incomingdata extends AsyncTask<Void,Void,Void>
{
Socket s ;
String input;
public Incomingdata(Socket socket)
{
super();
this.s = socket;
}
#Override
protected Void doInBackground(Void... params)
{
try
{
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
while(s.isConnected()&& r.hasNext())
{
String input =r.nextLine();
}
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(NoSuchElementException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void input)
{
System.out.println(""+input);
}
}
I have no errors and its not crashing buts its not listening to my incoming message coming in and it is not displaying it
Try using:
while(s.isConnected() && r.hasNext()) {
String input =r.nextLine();
}
Your while loop currently only checks to see if you are connected, and has the potential to be an infinite loop. Your Scanner, r, on the other hand will not have an infinite amount of data, so repeatedly calling nextLine() means you'll eventually run out of data to read, and get the NoSuchElementException that you have.
Edit: As codeMagic mentioned in the comments, you should call setText() on the UI thread in onPostExecute() and not in doInBackground() as that will just result in more exceptions once you fix this one.

Android Bluetooth as client i cant connect with my arduino

I have a problem, I can not establish a connection with my bluetooth shield, I've been with another application and if the device works, indicated by a light that is connected, but with this app, that does not happen. the app crashes when this method is called mmSocket.connect (), if this is not bad socket acquiring
  tmp = mmDevice.createRfcommSocketToServiceRecord (MY_UUID);
please help i am new to this =)
import java.io.IOException;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class ConfigView extends Activity implements OnClickListener, OnLongClickListener , OnItemSelectedListener {
Button bnt1;
Spinner listDevicesFound;
public BluetoothAdapter mBluetoothAdapter;
private BluetoothSocket mmSocket;
private BluetoothDevice mmDevice;
private final UUID MY_UUID = UUID.fromString("6170d0f0-5bc3-11e2-bcfd-0800200c9a66");
ArrayAdapter<String> btArrayAdapter;
String deviceToConnect;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.configview);
bnt1 =(Button) findViewById(R.id.button1);
bnt1.setOnClickListener(this);
bnt1.setOnLongClickListener(this);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
listDevicesFound = (Spinner) findViewById(R.id.spinner1);
listDevicesFound.setOnItemSelectedListener(this);
btArrayAdapter = new ArrayAdapter<String>(ConfigView.this, android.R.layout.simple_list_item_1);
listDevicesFound.setAdapter(btArrayAdapter);
registerReceiver(ActionFoundReceiver,new IntentFilter(BluetoothDevice.ACTION_FOUND));
//ScanDevices
btArrayAdapter.clear();
mBluetoothAdapter.startDiscovery();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(ActionFoundReceiver);
}
//Buttons Listeners
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1)
{
String address = deviceToConnect.substring(deviceToConnect.length() - 17);
Toast.makeText(getApplicationContext(), address, Toast.LENGTH_SHORT).show();
mmDevice = mBluetoothAdapter.getRemoteDevice(address);
BluetoothSocket tmp = null;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.button1)
{
try {
mmSocket.close();
} catch (IOException e) { }
}
return true;
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
btArrayAdapter.notifyDataSetChanged();
}
}};
public void onItemSelected(AdapterView<?> arg0, View v, int position,
long id) {
// TODO Auto-generated method stub
deviceToConnect = btArrayAdapter.getItem(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
deviceToConnect = "";
}
}
what is the UUID you are providing?
To get connected to any bluetooth profile running on a remote device, you need to establish socket connection with the UUID [of the service you want to connect.].
For details list on UUID of different services, refer to assigned numbers.pdf in www.bluetooth.org

strings over udp android

I can receive data on c# UDP server i have written through this code but instead of string i have typed in the editText box ... i receive android.widget.EditText#xxxxxx on the server. Some Help would be much appreciated.
package com.winmote.pro;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText editText1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
editText1 = (EditText) findViewById(R.id.editText1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String cmd= editText1.toString();
new nwcomm().execute(cmd);
}
});
}
private class nwcomm extends AsyncTask<String,Void,Void>{
#Override
protected Void doInBackground(String... text) {
// TODO Auto-generated method stub
String msg=text[0].toString();
InetAddress to = null;
try {
to = InetAddress.getByName("192.168.0.105");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int port=55505;
DatagramSocket soc = null;
try {
soc = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = msg.getBytes();
DatagramPacket pac = new DatagramPacket(data, data.length, to, port);
try {
soc.send(pac);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You need to ask for the contents of the EditText, not the String representation of the variable... Change this line:
String cmd= editText1.toString();
To:
String cmd = editText1.getText().toString();

Categories

Resources