It's my first question in here. I hope i can find answer. Subject is that, i have server (arduino). it send and receive data.it send data when take a data from client side(android). Android side is send data when push button. Also android has use Speech to Text (google API).So when we push button or use speechrecognation, client side send a data.But it reads socket continuously. I have two kind android device. One device work well about data receiving but it is not good about speechrecognation. One device very well about voice but after a while socket is happened useless. We must push reset button on arduino and reset android app. (My first android device version is 5.1.1 second is 6.0). Sorry for my english. I hope i can tell my problem :)
.
.
.
public void senddata(String asd){
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(asd);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
.
.
.
class ClientThread implements Runnable {
#Override
public void run() {
BufferedReader inStream = null;
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
//socket.setSoTimeout(1000);
// Get the input and output streams
inStream = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
// Confirm that the socket opened
// Read messages in a loop until disconnected
while( true){
String msg= inStream.readLine();
Log.e("GELENLER::::",msg);
gelenkomut=msg;
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
gelenparse(gelenkomut);
}
});
// Send it to the UI thread
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
finally {
try {
inStream.reset();
inStream.
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Related
I'm newer programer in android .. I need help
to sending text between two phone by wifi
first : server
second :client
I'm searching more but i need Simple code and easy to help me
thnx for advance
I guess sockets is what you are looking for...
To create a socket in android the socket must be created in a thread.
Client side example:
private final String IP = "9.9.9.9";
private final int PORT = 8080;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new MainThread()).start();
}
class MainThread implements Runnable {
#Override
public void run() {
try {
InetAddress address = InetAddress.getByName(IP);
socket = new Socket(address,PORT);
new Thread(new GetThread()).start();
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
class GetThread implements Runnable {
#Override
public void run() {
try {
InputStreamReader isR=new InputStreamReader(socket.getInputStream());
BufferedReader bfr=new BufferedReader(isR);
while(true) {
String textMessage = bfr.readLine();
// TODO: Insert logic which use the recived message (textMessage)
}
}
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
In the thread, the socket is waiting for data to be sent (while(true)).
and the IP is the ip of the server (if you are connecting to your computer
with wifi, you should check your ip address with ipconfig in the command line).
I am developping an Android app and a java desktop app. The Android app send to the java desktop the sms received, and the desktop app provide an interface for answering to these sms.
The android app is the server, the desktop app connects to it through a socket.
Here is the code of the server (android app side)
public class Server extends AsyncTask<Void, Void, Void> {
public void stopServ(){
this.run=false;
}
public void newSMSReceived(String sms, String phone){
//SEND THE NEW SMS TO THE DESKTOP APP
try {
outputStream.writeUTF(new String(sms.getBytes(),"ISO-8859-1"));
outputStream.flush();
outputStream.writeUTF(new String(phone.getBytes(),"ISO-8859-1"));
outputStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... params) {
ServerSocket ss = null;
try {
ss = new ServerSocket(TCP_SERVER_PORT);
Socket s = ss.accept();
System.out.println("connection received !");
inputStream = new ObjectInputStream(s.getInputStream());
outputStream = new ObjectOutputStream(s.getOutputStream());
outputStream.writeObject(contacts);
outputStream.flush();
while(true){
//READ THE MESSAGE SENDED FROM THE DESKTOP APP
message=inputStream.readUTF();
phone=inputStream.readUTF();
smsManager.sendTextMessage(phone.replaceFirst("0", "\\+33"), null, message, null, null);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
The desktop app side :
public class Main extends Application {
public Main(){
try {
PropertiesRetriever prop = new PropertiesRetriever();
socket = new Socket(prop.getIp(), 5657);
outputStream = new ObjectOutputStream(socket.getOutputStream());
inputStream = new ObjectInputStream(socket.getInputStream());
Thread listener = new Thread(new Runnable() {
public void run() {
while(true){
String message,phone;
Contact contact;
try {
//RECEIVED THE MESSAGE FROM THE ANDROID APP
message=inputStream.readUTF();<--- EOFException
phone=inputStream.readUTF();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
listener.start();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void sendMessage(Contact contact, Message message){
try {
//SEND THE MESSAGE TO THE ANDROID APP
outputStream.writeUTF(message.getTextUTF());
outputStream.flush();
outputStream.writeUTF(contact.getPhoneUTF());
outputStream.flush();
System.out.println(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**...**/
}
The details of the method "getxxUTF":
String rtr=null;
try {
rtr = new String(text.getBytes(),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rtr;
EOFException :
java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:340)
at java.io.ObjectInputStream$BlockDataInputStream.readUnsignedShort(ObjectInputStream.java:2818)
at java.io.ObjectInputStream$BlockDataInputStream.readUTF(ObjectInputStream.java:2874)
at java.io.ObjectInputStream.readUTF(ObjectInputStream.java:1073)
Thing is, at a point, I get an EOFException on the readUTF mentioned above. Everything works fine until a certain point, and I have no clue why... Someone ?
You get this not 'randomly' but when the peer has closed the connection.
Server part(Android)
new Thread(new Runnable() {
public void run() {
DatagramSocket s;
try {
s = new DatagramSocket();
s.send(new DatagramPacket("aaa".getBytes(), 3, InetAddress.getByName(/* Server ip address*/), 11720));
s.close();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(true)
{
try {
ServerSocket ssocket = new ServerSocket(11720);
ssocket.accept(); // Cannot make connection!!
Toast.makeText(a, "Who's coming", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
Client code (Java, PC)
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(11720);
DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);
ds.close();
try {
ds.receive(dp);
// ds.send(new DatagramPacket("aaaa".getBytes(), 4, dp.getAddress(), 11720));
Socket socket = new Socket(dp.getAddress(), 11720); // Cannot make connection!!
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I want to make connection between android server and pc client.
First android send a packet to pc.
I think server can know using this packet, so I use function getAddress().
Then android open socket using port number 11720 and pc try to connect android.
But it cannot connect.
Why this code cannot make connection?
Oh, I just want to know how can I connect from pc to phone.
So I change pc and android code.
Firstly, my goal is connect to android using static port(11720).
But I cannot make connection using static port when using LTE.
So I check socket information using simple program.
This is in pc.
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(11720);
DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);
while (true)
{
ds.receive(dp);
System.out.println(dp.getSocketAddress());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And this is in android.
new Thread(new Runnable() {
public void run() {
try {
DatagramSocket s = new DatagramSocket(11720);
while(true)
{
s.send(new DatagramPacket("aaa".getBytes(), 3, InetAddress.getByName("143.248.55.131" /* Server address */), 11720));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
I execute programs using WiFi and LTE.
And result is
/143.248.56.118:11720 <- using WiFi
/143.248.56.118:11720
/143.248.56.118:11720
/117.111.7.124:35645 <- change LTE
/117.111.7.124:35645
/117.111.7.124:35645
When using LTE, socket's port number is changed.
so I cannot send packet using static port number.
How can I solve this problem?
Firstly, why are you complicating by using Datagram Socket unnecessarily?
You can simply use TCP without any problems.
Well, your client code(Java PC) might be waiting at:
ds.receive(dp);
And so the socket might not get created.
Although the android program is sending a packet but UDP being unreliable, the packet may not be received by the client code.
Also, this can be due to network issues like both cannot get a connection, or there might be a NAT between them which would not let any UDP packet to let in.
So, I would suggest to simply use TCP. Don't complicate by first sending a UDP packet and then connecting with TCP.
That is my program in java for my android app. I tried to create tcp connection with tcp server. I can connect to server with another applications so that i can send and receive from tcp server. With my code and with my program i can send messages to server very eazy, but i have troubles with receiving messages from server.
private Socket socket;
private final int SERVERPORT = 6060;
private final String SERVER_IP = "192.168.0.8";
public TextView tv;
private PrintWriter out;
private InputStream in;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)this.findViewById(R.id.textView1);
new Thread(new ClientThread()).start();
}
Here is my problem i dont know how to receive strings or bytes from server. When i run my app on phone it closes the open window and say that program stop working. If i delete this section of code(public void ONCLICK2) i can transmit messages to server.
public void ONCLICK2(View view) {
try {
in=socket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte array[]=new byte[1];
try {
int i=in.read(array);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So please help me with that section of code. How can i receive string send from TCP server.
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.editText1);
String str = et.getText().toString();
out.println(str);
out.flush();
}catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Simply put, the problem is you are intercepting the byte array of an unknown length and attempting to store them in array the size of one. Furthermore, it is ideal to append the packet size prior to the data in the packet and perhaps create the intercept in a separate thread waiting for incoming packets.
To just fix your ONCLICK2 you should do the following:
byte[] data = new byte[6556];
try {
in = socket.getInputStream();
// NOTE: The data byte array will contain empty values if
// under the size of 6556
int size = in.read(data);
// send to LogCat
Log.e("String", data.toString());
} catch (Exception e) {
e.printStackTrace();
}
I have not tested this code, but this should fix your problem.
I'm trying to write this program which updates itself on the current status of a variable. How I intended it to work is by having a timed task to constantly send the string "update" to the server. The server will recognize the string and will send the necessary values for the variable on the android device. However, I am facing some problems. The string "update" is sending without error but when the corresponding value from the server is sent back, the program does not seem to be able to read the reply. Here is the code:
//Open socket and initialize data streams
try {
socket = new Socket(serverIpAddress, applicationport);
//in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in = new DataInputStream(socket.getInputStream());
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
} catch (UnknownHostException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
ShowDialog("Login Error" + ex.getMessage());
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
ShowDialog("Login Error" + ex.getMessage());
}
//Create new daemon timer
updateData = new Timer(true);
updateData.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
out.println("update");
UpdateMethod();
}//run
}, 1000, 10000);//schedule the delays start/interval here
};
private void UpdateMethod() {
//This method is called directly by the timer
//and runs in the same thread as the timer.
//It calls the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
};//timermethod
private Runnable Timer_Tick = new Runnable() {
public void run() {
try {
//in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//String getx1 = null;
//getx1 = in.readLine();
//if (getx1 != null) {
//float updatex1 = Float.parseFloat(getx1);
//get_x1 = getx1;
//}
in = new DataInputStream(socket.getInputStream());
/*try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
x1display = (TextView) findViewById(R.id.x1display);
x1display.setText(in.readUTF());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (in != null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
};
As you can see, I have tried experimenting with both DataInputStream and BufferedReader as well but to no avail.
Edit: It seems that trying to read from the input stream is causing my UI to freeze up. I have no idea what is wrong as my code seems to be without errors..
Any help or advice would be greatly appreciated!
Thank you!
The code looks fine to me. But its not working so looks like you need to chop it up.
Test if the socket stuff is working without the Timer. Make a socket connection and read its response without the Timer and UI code
If that works, introduce the Timer but not the UI code
If that works, do the whole thing (which is failing now)
Somewhere in this test process you should be able to find the culprit
As you have already said, reading blocks the thread. You shouldn't ever read something inside the UI thread! Furthermore, as I remember correctly, closing input before closing output does some nasty things. I would suggest closing the socket instead and putting the BufferedReader back in. This is how it should look like:
//Open socket and initialize data streams
try {
socket = new Socket(serverIpAddress, applicationport);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
} catch (UnknownHostException ex) {
ex.printStackTrace();
ShowDialog("Login Error" + ex.getMessage());
} catch (IOException ex) {
ex.printStackTrace();
ShowDialog("Login Error" + ex.getMessage());
}
//Create new daemon timer
updateData = new Timer(true);
updateData.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
out.println("update");
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
x1display = (TextView) findViewById(R.id.x1display);
x1display.setText(in.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
});
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}}, 1000, 10000);//schedule the delays start/interval here
By the way, don't use printStackTrace(): Why is exception.printStackTrace() considered bad practice?