Android - UDP Client Error - java

I have a little C++/Java - Socket Server (UDP) running on my PC.
Now, i want to connect with my Android App to the Server. But when i send a package my App crash.
public void Socketinit() {
// 1. Socket erstellen!
try {
serverAddr = InetAddress.getByName("192.168.0.101");
socket = new DatagramSocket();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
createListeners();
}
and
entprivate void createListeners() {
confirm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
buf = input.getText().toString().getBytes();
DatagramPacket packet = new DatagramPacket(buf,buf.length, serverAddr, SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
It crashs on "socket.send(packet);"
I can connect to my Server via C++ so the Server is up and running. Where is the Clientproblem in my code ?
thanks

You are propably getting the NetworkOnMainThreadException (see Logcat or check in the debugger).
You can use an AsyncTask to resolve this.
Propably you are also missing the Internet permission in the manifest.
Here are further details: How to fix android.os.NetworkOnMainThreadException?

Related

How to send and receive multiple data from client to server

I have established a connection between java server and android client using sockets. I can send messages from android to java, but only 1 message at a time.
what if I want to send data of 2 variables from android to java and at the same time receive those data in java in 2 different variables.
How can I achieve this.??
Code for Android Client
public class MessageClient extends Activity implements OnClickListener {
EditText etMessage;
Button bSend;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messageclient);
bSend = (Button) findViewById(R.id.button1);
etMessage = (EditText) findViewById(R.id.etMessage);
bSend.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
try {
Socket s = new Socket("192.168.0.100",7000);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(etMessage.getText().toString());
dos.flush();
dos.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Code for java server
public static void main(String arg[]){
Thread t = new Thread(){
public void run() {
// TODO Auto-generated method stub
try {
ServerSocket ss = new ServerSocket(7000);
while(true){
Socket s = ss.accept();
System.out.println("Server is running");
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Received from client: "+dis.readUTF());
dis.close();
s.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
Thank you.
You are just sending a String and then closing the socket.You can try to send lists and also can send multiple DataInputStream dis without closing the socket connection.

Error in Asmack Android Connection to Server Xmpp

I cant connect to the server i dont know why please help me. This is my code :
public class Sample extends Activity{
/** Called when the activity is first created. */
TextView tvHello;
XMPPTCPConnection connection;
ConnectionConfiguration config;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvHello = (TextView) findViewById(R.id.tvHello);
Log.i("ohyeah", "I'm here");
config = new ConnectionConfiguration("host", 5222, "servername");
connection = new XMPPTCPConnection(config);
try {
connection.connect();
// tvHello.setText("Connected to XMPP server");
Log.i("ohyeah", "Successfully Connected");
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ohyeah", "Not Connected");
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("ohyeah", "Something Fishy");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("ohyeah", "yes");
}
}
}
this is my error:
http://i.stack.imgur.com/iaRdO.png
You can not do long or background running process in ui thread so try to use AsyncTask to connect xmpp server :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvHello = (TextView) findViewById(R.id.tvHello);
Log.i("ohyeah", "I'm here");
connectToXmppServer();
}
public void connectToXmppServer(){
new AsyncTask<Void,Void,String>(){
#Override
protected String doInBackground(Void... params) {
config = new ConnectionConfiguration("host", 5222, "servername");
connection = new XMPPTCPConnection(config);
try {
connection.connect();
// tvHello.setText("Connected to XMPP server");
Log.i("ohyeah", "Successfully Connected");
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ohyeah", "Not Connected");
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("ohyeah", "Something Fishy");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("ohyeah", "yes");
}
return null;
}
}.execute();
}

Unable to connect BluetoothSocket to Arduino

I am currently trying to receive data on my android smartphone (version 4.4.4) send from my RFduino (some kind of arduino) via Bluetooth. Therefore i made a small android application.
Now everything works fine, until i try to connect my BluetoothSocket. First i got the an IOException: read failed -1 which i tried to solve like this:
IOException: read failed, socket might closed - Bluetooth on Android 4.3
Which worked. But now my application just freezes after i call connect(). I know that this is because the method blocks until it has found a connection, but why does this not connect?
My RFduino uses BluetoothBLE (low energy): Do i have to use the BluetoothGatt classes as counter-part?
Here is my code:
public BluetoothConnection(Activity parentActivity) {
this.mActivity = parentActivity;
findBluetooth();
openBluetooth();
}
private void findBluetooth() {
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (this.mBluetoothAdapter == null) {
}
if (!this.mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
this.mActivity.startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = this.mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals("RFduino")) {
this.mBluetoothDevice = device;
break;
}
}
}
}
private void openBluetooth() {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
try {
BluetoothSocket tmp = this.mBluetoothDevice.createRfcommSocketToServiceRecord(uuid);
this.mBluetoothSocket = new NativeBluetoothSocket(tmp);
this.mBluetoothSocket.connect();
} catch (IOException e) {
// try the fallback
Log.w("BT", "Had to use fallback method!");
try {
this.mBluetoothSocket = new FallbackBluetoothSocket(this.mBluetoothSocket.getUnderlyingSocket());
Thread.sleep(500);
this.mBluetoothSocket.connect();
} catch (FallbackException e1) {
Log.w("BT", "Could not initialize FallbackBluetoothSocket classes.", e);
} catch (InterruptedException e1) {
Log.w("BT", e1.getMessage(), e1);
} catch (IOException e1) {
Log.w("BT", "Fallback failed. Cancelling.", e1);
}
}
try {
this.mInputStream = this.mBluetoothSocket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
While NativeBluetoothAdapter and FallbackBluetoothAdapter are depicted in the thread i posted above.
Thanks for any suggestions.

Android client Socket throws SocketException:

I am trying to implement java socket client in android and my server is my laptop. I want my android mobile to connect to laptop by java socket. But i am getting exception on client side: "SocketException" and it looks to me because of the socket() call not able to create socket properly. Below is my android client side code for review. Is there any solution to the resolve the exception:
public class SimpleActivityExampleActivity extends Activity {
/** Called when the activity is first created. */
private String usrName;
private String vendorName;
private String message;
public Socket socket;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void submitTheForm(View view) {
final EditText edittext1 = (EditText) findViewById(R.id.editText1);
final EditText edittext2 = (EditText) findViewById(R.id.EditText01);
final EditText edittext3 = (EditText) findViewById(R.id.editText2);
usrName = edittext1.getText().toString();
vendorName = edittext2.getText().toString();
message = edittext3.getText().toString();
message = usrName+ "," + vendorName + "," + message;
byte[] msg = message.getBytes();
try {
InetAddress serverAddr = InetAddress.getByName("192.168.1.2");
Log.d("ClientActivity", "C: Connecting...");
socket = new Socket(serverAddr, 2200);
socket.getOutputStream().write(msg);
socket.getOutputStream().flush();
} catch (UnknownHostException e) {
Toast.makeText(SimpleActivityExampleActivity.this, "unknownhostException", Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketException e) {
// TODO Auto-generated catch block
Toast.makeText(SimpleActivityExampleActivity.this, "Sockexception", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
//System.out.println("in IOexception for sure");
Toast.makeText(SimpleActivityExampleActivity.this, "IOexception", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
catch (Exception e){
Toast.makeText(SimpleActivityExampleActivity.this, "Exception", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}finally {
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
submitTheForm() function is invoked on a button click from main.xml file "android:onClick = "submitTheForm"
Have you set the
<uses-permission android:name="android.permission.INTERNET" />
permission?
Found this here
Is it possible that you forgot to add the Internet permission to your manifest file?
<uses-permission android:name="android.permission.INTERNET" />

Java Sockets - transmission in real time

i got this code form Android-er blogspot, big thanks for him to make me almost understand basic socket connections in java. So i got this client app on my android device, and computer with server running, but how could i make a loop in a client code, to make it send data from EditText in real time? (whenever it changes) Please if someone could clear it out for a complete newbie?
-----This is client code (Android-er Copyrights):
package com.exercise.AndroidClient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.101", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}};
}
-----This is server code (Android-er Copyrights):
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
There are a few things you will need to change.
First of all, if you want the data to be sent in real time, you will need to change from using a Button OnClickListener to using a TextWatcher (see addTextChangedListener in TextView)
As this event will be fired every time the text changes, you will need to open your socket outside of the event (you don't want a new socket each time some text is typed), and then in your listener, you just want to send the new data down the socket.
You can set a text changed listener on your EditText and do the sending from there.
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
// ... do your sending here
}
But beware that if that sending is not asynchronous, it may block text entry for the user. Network latency can be relatively high on GSM networks, so the user may be irritated, when his freshly typed characters will not immediately appear on screen.

Categories