Sending UDP packet from Android to Arduino - android

I'm new to android development so please be gentle :p I'm having trouble sending UDP packets from my android phone to my anrdiuno (with WiFi shield). I can send and recieve packets to or from the arduino using the TCP/UDP Terminal app from the Play Store, with no problems. For an easy beginners task I would like to send just one packet to my arduino (which is on my local network at address 192.168.0.101 and listens on port 5000), when I press a button, a message is then displayed saying that data has been sent. My current android code is below:
//CALLED WHEN USER PRESSES BUTTON
public void sendMessage(View view){
runUdpClient();
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText("MESSAGE SENT");
// Set the text view as the activity layout
setContentView(textView);
}
private void runUdpClient() {
try{
String msg = "Hello";
byte[] msgBytes = (msg.getBytes());
String serverHostname1 = new String ("192.168.0.101");
InetAddress ip = InetAddress.getByName(serverHostname1);
//SEND ON PORT 5000
DatagramSocket socket = new DatagramSocket(5000);
socket.setBroadcast(true);
DatagramPacket packet = new DatagramPacket(msgBytes,msgBytes.length, ip, 5000);
//packet.setAddress(ip);
//packet.setPort(5000);
socket.send(packet);
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
I have debugged the code and found that an exception is thrown when socket.send(packet) is called, (although i do not know how to view this expection). After stepping through the send function, this exception was thrown:
IllegalArgumentException("Packet address mismatch with connected address");
Please could someone help me with this please? Thank you ever so much for any help given :)

found a solution to this problem. If anyone else gets this problem the solution is to call the udp packet send function from inside a thread as such:
public void sendMessage(View view){
final EditText editMessage = (EditText) findViewById(R.id.edit_message);
final String message = editMessage.getText().toString();
new Thread(new Runnable(){
#Override
public void run() {
try {
runUdpClient(message);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
Found out that most communications need to be done inside a thread. Peace.

Related

I cannot send a DatagramPacket through DatagramSocket from Samsung S9+ (I use another thread than UI thread)

I try to send a UDP packet from my mobile to a PC – IP 192.168.1.113, at the PC I use “Packet sender”with UDP server port 55777.
But it does not work, I have sent UDP packet from a VBA script in Excel to the Packet sender and it works, I can also send through
UDP apps I have downloaded to the mobile, to the “Packet sender”.
I use:
Android Studio 3.5
SDK platform 8.1
Mobile: Samsung S9+
I have added the INTERNET permission to the manifest:
I send the packet from a new thread since the main thread does not allow to send packages, the below code is the first step before I continue, need to make this to work first though.
public class MainActivity extends AppCompatActivity {
private Handler mainHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startThread(View view) {
ExampleRunnable runnable = new ExampleRunnable(10);
new Thread(runnable).start();
}
class ExampleRunnable implements Runnable {
#Override
public void run() {
DatagramSocket ds = null;
String message = "Hello";
try{
ds = new DatagramSocket();
InetAddress serverAddr = InetAddress.getByName("192.168.1.113");
DatagramPacket dp;
dp = new DatagramPacket(message.getBytes(), message.length(), serverAddr, 55777);
ds.send(dp);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
}
}
}
There is several things to be confirmed before answering the question. You can provide stack trace or any error if there is any. In your case, If there is no programming error, You should check your firewall once. Add new firewall rule for the incoming connection request on port 55777.

serversocket to bluetooth serversocket

For the past couple of days, I have been working on establishing a client-server socket over Bluetooth with an android server and a windows PC socket so I can send information over from the computer that can be used on an app for Oculus Gear VR (app would be on the android). I am having a big issue with the Bluetooth server socket on the android side. It doesn't help that my experience with android studio is encompassed within like 4 days. I figured out how to create a regular server socket on an android app that waits for a connection from the client
`public class MyServer {
BluetoothDevice device;
Thread m_objThread;
ServerSocket m_server;
String m_strMessage;
DataDisplay m_dataDisplay;
Object m_connected;
public MyServer()
{
}
public void setEventListener(DataDisplay dataDisplay)
{
m_dataDisplay = dataDisplay;
}
public void startListening()
{
m_objThread = new Thread(new Runnable() {
public void run() {
try {
m_server = new ServerSocket(2001);
Socket connectedSocket = m_server.accept();
Message clientmessage = Message.obtain();
ObjectInputStream ois = new ObjectInputStream(connectedSocket.getInputStream());
String strMessage = (String) ois.readObject();
clientmessage.obj = strMessage;
mHandler.sendMessage(clientmessage);
ObjectOutputStream oos = new ObjectOutputStream(connectedSocket.getOutputStream());
oos.writeObject("Hi..");
ois.close();
oos.close();
m_server.close();
} catch (Exception e) {
Message msg3 = Message.obtain();
msg3.obj = e.getMessage();
mHandler.sendMessage(msg3);
}
}
});
m_objThread.start();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message status)
{
m_dataDisplay.Display(status.obj.toString());
}
};
`
But I am not completely sure how to change this to a Bluetooth server socket in order to create a Bluetooth socket. Any help is appreciated, I am relatively new to coding and have only used c++ on visual studio so I am having a lot of trouble with android studio. Thanks!
You should create one thread for accepting a connection and another- for sending and receiving the data. When device is connected, you stop 'connect thread' and start 'transfer' thread. There is a gread example from google- https://github.com/googlesamples/android-BluetoothChat

server socket multithreading confuses with the devices

I'm writing an Android app using sockets for communication. In a class called sever I accept clients (android devices) and open sockets for them.
Server side:
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Socket socket = serverSocket.accept();
Client clientThread = new Client(socket);
System.out.println("New client: " + clientThread.getName());
new Thread(clientThread).start();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
After a succesful connection the user may create a group, which is like a room for number of clients to connect and play together.
The group creation is done here:
Server side:
Client:
private void client_create() {
this.mGroup = new Group();
mGroup.joinPlayer(this);
System.out.println("New group for: " + name);
}
Group:
public Group(int nClients){
// Clients in this group
this.clients = new ArrayList<Client>();
}
public void joinPlayer(Client player){
clients.add(player);
}
Client Side:
Connection handling:
try {
socket = new Socket(hostName, portNumber);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
Listener listener = new Listener();
new Thread(listener).start();
} catch (IOException e) {
e.printStackTrace();
}
I ran this programm on 2 android devices and on my localhost as the server. After the connection was made, I tried creating 2 independent different groups. While debugging it all seems legit until I reached to a point where I lost it due to the 2 different running threads.
The odd thing that happened is that after the first group was created with the first client (clients contains the first device client object), and then the second group with the second player (clients contains the second device client object), the first group clients array contains the second client object (from the second device).
Have you got any thoughts on that? Did I do something wrong?
Figured it out.
Clients was mistakly defined as static, so I guess when accessing to the clients array of the static object it received the last one who was created.

How to send a text message to a paired device through bluetooth in android?

In my app I want to send and receive text message through bluetooth. I can see in my listview a list of paired device name and address.But when I am trying to send a text to a paired device nothing happens. In other device there is no text received.
This is my Code to send message to a paired device.
private void sendDataToPairedDevice(String message, String adress) {
byte[] toSend = message.getBytes();
try {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adress);
// BluetoothSocket socket
// =device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"));
BluetoothSocket socket = null;
Method m = null;
try {
m = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
} catch (Exception e) {
e.printStackTrace();
}
try {
socket = (BluetoothSocket) m.invoke(device, 1);
} catch (Exception e) {
e.printStackTrace();
}
OutputStream mmOutStream = socket.getOutputStream();
mBluetoothAdapter.cancelDiscovery();
socket.connect();
mmOutStream.write(toSend);
} catch (Exception e) {
Log.d("TAG", "Exception during write", e);
}
}
the bluetoothchat sample is actually the perfect thing to use if you are new in using the bluetooth api.
assuming that you are using only one Activity for your application which is the BluetoothChat class :
for sending text to the device you are connected to, use the "sendMessage(String message)" method in the BluetoothChat class to send text.
as for receiving and handling the text, you will find also handleMessage(Message msg) method somewhere in the bluetoothchat class then go this part:
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
see the readMessage String?
this is the text that that you receive from the other device , now you can handle it as you want.
then simply change the main layout that the BluetoothChat class refers to, then in BluetoothChat chat either comment or delete the parts that have errors which actually will be the parts in the UI u have deleted or changed.
i know the code may sound messy but this is the easiest way to use it quickly as possible and watching video tutorials or text tutorials for hours will just make it more complicated, believe me i tried this before.

android TCP client unable to display data sent from C Server via wi-fi

I'm kinda new to android socket programming. My android program simply connects to a server (written in c,executed in the console) and must display the content being sent from the server (something like "hi client"). I have textview's for displaying whether the connection is being established or not and another edittext for sending the client's message to the server. The system is connected via Wi-fi. The server is able to recieve messages from my android client but android client is not displaying the message sent by the server. The code snippet for the reading from server part is:
private TextView MsgFromServer; //defination
// here is the code for the connection and starting new thread etc
final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
handler.post(new Runnable() {
#Override
public void run() {
try {
while((line=in.readLine())!=null){
MsgFromServer.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Also I tried doing something like this:
final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
line=in.readLine().toString(); //string type
handler.post(new Runnable() {
#Override
public void run() {
MsgFromServer.setText(line);
}
}
both approaches are not working for me.The message I send from the client to the server reaches there properly whereas the other direction communication is not happening. Also I've tested my C server with a simple C client and the message passing is happening smoothly.
How does the client behave? Is it waiting at in.readLine() ?
Be sure the server sends "Hi client\n" (with the lineend).
in.readLines() only returns when a lineend \n is found.
Is the new Runnable running? If you change the code
a little to
try {
MsgFromServer.append("going to read a line..");
while((line=in.readLine())!=null){
MsgFromServer.append(line);
}
then do you see that?

Categories

Resources