I have a code that sends data on click. However, I want to send data repeatedly with a fixed time interval.
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} 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);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
any help would be appreciated.
Create a new thread with a while loop and a Thread.sleep() call.
This post has all the code you need:
How to run a Runnable thread in Android?
Related
I have looked all over for a solution to this problem, I have not come up with a solution that works.
Currently, I send and receive packets on my android device emulator using my loopback/localHost address. This proccess works successfuly, however when I try running the same code using my computer's public address the server never receives the packets.
private String hostName = "99.248.222.229";
//private String hostName = "10.0.2.2";
private InetAddress hostAddress;
#Override
protected void onCreate(Bundle savedInstanceState)
{
CreateAddress addressGetter = new CreateAddress();
try {
hostAddress = addressGetter.execute(hostName).get();
} catch(Exception e){
e.printStackTrace();
}
Button btnLock = (Button) findViewById(R.id.btnLock);
btnLock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendReceiveTask = new runUdpClient();
byte[] udpMsg = {(byte)housenumber, (byte)doornumber, LK_MSG, UNLOCK};
System.out.println(hostAddress);
sendPacket = new DatagramPacket(udpMsg, udpMsg.length, hostAddress, portnumber);
DatagramPacket receivePacket = null;
try {
receivePacket = sendReceiveTask.execute(sendPacket).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
currentDoorState = (receivePacket.getData()[3]==UNLOCK);
updateDoorStatus(currentDoorState);
int doorNum = doornumber;
eventArrayList.add(0, (getCurrentTimeStamp() + eventString.replace("doornum", Integer.toString(doorNum)))+ ((currentDoorState) ? "unlocked." : "locked."));
adapter.notifyDataSetChanged();
}
});
}
private class runUdpClient extends AsyncTask<DatagramPacket, Void, DatagramPacket>{
#Override
protected DatagramPacket doInBackground(DatagramPacket ...params){
DatagramSocket ds = null;
//SEND
try {
ds = new DatagramSocket();
DatagramPacket dp;
//dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), hostAddress, portnumber);
dp = params[0];
ds.send(dp);
} catch (SocketException e) {
e.printStackTrace();
}catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//RECEIVE
DatagramPacket incomingPacket = new DatagramPacket(new byte[100], 100);
try {
ds.setSoTimeout(1000);
} catch (SocketException e) {
e.printStackTrace();
}
try {
ds.receive(incomingPacket);
} catch (IOException e){
e.printStackTrace();
}finally{
if(ds != null) ds.close();
}
System.out.println("Packet recieved from server" + Arrays.toString(incomingPacket.getData()));
return incomingPacket;
}
}
Android send data to pc - client side (work with success):
Button send = (Button) findViewById(R.id.sendSocket);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Socket socket = new Socket("IP",8000);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("Hello");
socket.close();
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Now How can i keep listening to receive data from pc (server side) ???
that's what i am tryng (not working) :
try {
Boolean end = false;
ServerSocket ss = new ServerSocket(8000);
while(!end){
//Server is waiting for client here, if needed
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
recive.setText(st);
s.close();
//if ( STOPPING conditions){ end = true; }
}
ss.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recive.setText(e.toString());
}
try something like this :
ServerSocket ss = new ServerSocket(8000);
Socket s = ss.accept();
BufferedReader input = new BufferedReader (new InputStreamReader (s.getInputStream ()));
while (true)
{
String st = "";
try
{
st = input.readLine ();
System.out.println (st);
}
catch (IOException e)
{
//error ("System: " + "Connection to server lost!");
System.exit (1);
break;
}
}
ss.close();
I use these codes for communicating between devices. If i close or kill the client app, the server app gets thousands of useless data. The textView in the server side is full of this: Client says: null. If i close the client twice, the server stops with StackOverFlowError. How can i make the code to dont send this null values when the app stops? Or can i filter the server side to do nothing when getting this data?
Client:
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.0.2.2";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} 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);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
Server:
public class Server extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 1599;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.text2);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
I think you should use a delimiter character, to tell the Server your Client it's about to die. Add that character of code in onPause method of your Android Activity/Fragment.
Then in your Server, just get the String or byte and compare it against your Delimiter String/Character and stop the Server listening for the Connection.
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
The problem is here. You aren't checking the result of readLine() for null. If it returns null, the peer has closed the connection and you should do likewise, and exit this loop. You can probably get rid of the isInterrupted() test as well.
Also, if you get any IOException other that a read timeout when reading from a socket, the connection is dead and you must close the socket and exit your loop.
I want my app to connect to a server. I only want the client.
protected void onCreate(Bundle savedInstanceState) {
//...
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
//...
} catch (IOException e1) {
//...
}
}
But the application just crashes. I started this activity by pressing a button.
Do you know what the problem could be?
You need to perform all your blocking processes in a Thread, and release the main UI Thread, for example:
protected void onCreate(Bundle savedInstanceState) {
//...
new Thread(){
public run(){
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
//...
} catch (IOException e1) {
//...
}
}
}.start();
}
i want to send a udp packet from my laptop to an android device, i write a simple App for that but it doesn't work, i think that the port(5554) that i have been used is the problem.
Code:
`private void runUdpServer()
EditText RecieveText = (EditText) findViewById(R.id.editText1);
EditText check = (EditText) findViewById(R.id.editText2);
String lText;
byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN];
DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
DatagramSocket ds = null;
RecieveText.setText("try1");
try {
RecieveText.setText("try2");
ds = new DatagramSocket(UDP_SERVER_PORT); // i think the problem is here
//disable timeout for testing
if (ds != null){RecieveText.setText("connected");}
else {RecieveText.setText("not connected");}
RecieveText.setText("try");
ds.receive(dp);
lText = new String(lMsg, 0, dp.getLength());
Log.i("UDP packet received", lText);
RecieveText.setText(lText);
check.setText("port opened");
} catch (SocketException e) {``
check.setText("SocketException");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
check.setText("port didn't open");
} finally {
if (ds != null) {
ds.close();
RecieveText.setText("not connected1");
}
else {RecieveText.setText("not connected1");}
}
check.setText("end");
if (ds != null){RecieveText.setText("connected");}
else {RecieveText.setText("not connected");}
}
}
I dont think it is a port issue... print your error log to have a better idea of faillure.... any way try this ... not checked for any typo.... Also keep in mind that any networking task is better to be inside an async task...
int port =1855; ///any port that you want > 1024
DatagramSocket socket = null;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
try {
socket.setBroadcast(true);
} catch (SocketException e) {
e.printStackTrace();
}
//////send socket
int eport = 1616;
InetAddress eip = null;
try {
eip = InetAddress.getByName("192.168.1.1"); ////SERVER IP ADDRESS
} catch (UnknownHostException e) {
e.printStackTrace();
}
DatagramSocket esocket = null;
try {
esocket = new DatagramSocket(eport);
} catch (SocketException e) {
e.printStackTrace();
}
///SENDING
byte[] send= new byte[60*1024];
DatagramPacket send_packet = new DatagramPacket(send, send.length);
try {
socket.send(send_packet);
} catch (IOException e) {
e.printStackTrace();
}
//////Start receive
while(true)
{
byte[] message = new byte[60*1024];
DatagramPacket recv_packet = new DatagramPacket(message, message.length);
try {
socket.receive(recv_packet);
} catch (IOException e) {
e.printStackTrace();
}
///Do something whit recv_packet
}