I'm trying to send data from arduino to android app through esp8266. For the moment, arduino and android app are connected via the esp8266 using the TCP/IP socket API. However, when trying to send data continuosly from the arduino it's recieved only once by the android app. In fact, the message is well received by the app only when I proceed the AT+CLOSE command to close the socket and end communication. This method enables me to get the data only one time. So, I have tried to try configure the communication another time after closing it ( please check my code)
void loop()
{
if(Serial1.available())
{
Serial.println("heeeere");
int connectionId = Serial1.read()-48;
while(analogRead(4)>0)
{
convertedvalue = String((analogRead(4)*5)/1024); //convert read analog value before sending it to the android app
convertedvaluelength = String(convertedvalue.length()); //get the length of the converted value
content = "Converted value is "; //make the response to be send to the android app
content += convertedvalue; //make the response to be send to the android app
sendCIPData(connectionId,content);
sendData("AT+CIPCLOSE=0\r\n",1000,DEBUG); //close the connection
delay(10000);
sendData("AT+CIPSERVER=0\r\n",1000,DEBUG); // turn off server
delay(10000);
sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
delay(10000);
}
}
}
Android code :
package com.example.youssefguirat.socketseverywhere;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
Client(String addr, int port,TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse=textResponse;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
socket.sendUrgentData(16);
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/* #Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
textResponse.setText(values[0]);
Toast.makeText(MainActivity.this,"Server:"+values[0], Toast.LENGTH_LONG).show();
Log.w("MSG","Updating with msg");
}*/
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
public class MainActivity extends Activity {
Button buttonSend;
TextView textViewSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSend = (Button) findViewById(R.id.buttonSend);
textViewSocket = (TextView) findViewById(R.id.textViewSocket);
buttonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Client myClient = new Client("192.168.1.25",80,textViewSocket);
myClient.execute();
}
});
}
}
As you can see, I put a long delay in order to get correct and significant answer from the esp8266 but it didn't work :(busy response when trying to close and configure the server each time I send data
So, can someone help me with it ! I'm really stuck :(
Related
I have an app which has to poll a TCP server (on LAN) to fetch some data, I'm doing this using sockets in an AsyncTask class.
It works well for the first few requests. But at a certain point, the app must poll the server every 2s (using a timer). This is when the AsyncTask stops executing and the TCP messages do not get sent to the server. I can't figure out why.
Code is below. Any help will be appreciated!
Thank you!
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class TcpTask extends AsyncTask<String, Void, String> {
Context context;
TcpResultListener tcpResultListener;
int actionCode;
String TAG = "TcpTask";
String SERVER_IP = "192.168.1.12", SERVER_PORT = "1234";
Socket socket = null;
PrintWriter out;
int readTimeout;
// Creating listener
public void setOnTcpResultsListener(TcpResultListener tcpResultListener, int actionCode) {
this.tcpResultListener = tcpResultListener;
this.actionCode = actionCode;
}
// Constructor with context as parameter
public TcpTask(Context context, int timeout) {
this.context = context;
this.readTimeout = timeout;
}
#Override
protected String doInBackground(String... params) {
String result = null;
try {
//Create a client socket and define internet address and the port of the server
socket = new Socket(params[0], Integer.parseInt(params[1]));
Log.d(Constants.TAG, "Socket created");
//Setting timeout for readLine
socket.setSoTimeout(readTimeout);
Log.d(Constants.TAG, "Timeout set");
//Get the output stream of the client socket
out = new PrintWriter(socket.getOutputStream(), true);
Log.d(Constants.TAG, "PrinterWriter created");
//Write data to the output stream of the client socket
out.println(params[2]);
Log.d(Constants.TAG, "Sending TCP data: " + params[2]);
//Get the input stream of the client socket
InputStream is = socket.getInputStream();
//Buffer the data coming from the input stream
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//Read data in the input buffer
result = br.readLine();
} catch (NumberFormatException e) {
Log.d("TcpException", e.toString());
} catch (UnknownHostException e) {
Log.d("TcpException", e.toString());
} catch (IOException e) {
Log.d("TcpException", e.toString());
}
try {
Log.d(Constants.TAG, "Socket:: " + socket);
if(socket != null){
socket.close();
}
} catch (IOException e) {
Log.d(Constants.TAG, e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
Log.d(Constants.TAG, "String:: " + result);
tcpResultListener.onResultsReceived(result, actionCode);
}
}
The method I use to call the AsyncTask:
void sendTCP(String msg) {
TcpTask tcpTask = new TcpTask(this, 8000);
// Setting listener for tcpTask to send back result
tcpTask.setOnTcpResultsListener(AddSpaceActivity.this, 1);
// TODO: Change the data being passed below
//Pass the server ip, port and client message to the AsyncTask
tcpTask.execute(gwIP, gwPort, msg);
}
EDIT: Timer code:
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Log.d(Constants.TAG, "Timer fired:: " + firstReceived);
if(firstReceived){
sendTCP(Constants.NETWORK_STATUS_REQUEST);
}
}
}, 3000, 2000);
I am trying to develop an app in which
1.client sends request to server for connection(IP address+PORT no.)+sends data using "PrintStream"+Tries to read the data from Server(Using Inputstream)
2.Client creates the socket.
3.Server reads the data send by Client
4.SERVER writes the data using "PrintStream" at same time point no 3.
Problem is at point 4 Data written by SERVER is not Read by "INPUTSTREAM" of client(Point 1)
I dont know these Simultaneous operation are possible or not.If possible then how.If not then what is the alternate way?
Server Code
package com.example.loneranger.ser;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
public class MainActivity extends Activity {
TextView ip;
TextView msg;
String data = "";
ServerSocket httpServerSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
ip.setText(getIpAddress() + ":"
+ 8080 + "\n");
Server server = new Server();
server.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (httpServerSocket != null) {
try {
httpServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "IP: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
private class Server extends Thread {
#Override
public void run() {
Socket socket = null;
try {
httpServerSocket = new ServerSocket(8888);
while(true){
socket = httpServerSocket.accept();
HttpResponseThread httpResponseThread =
new HttpResponseThread(
socket);
httpResponseThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class HttpResponseThread extends Thread {
Socket socket;
HttpResponseThread(Socket socket){
this.socket = socket;
}
#Override
public void run() {
BufferedReader BReader;
PrintWriter printer;
String request;
try { InputStream inputStream = socket.getInputStream();
BReader = new BufferedReader(new InputStreamReader(inputStream));
request = BReader.readLine();
Thread.sleep(500);
printer = new PrintWriter(socket.getOutputStream(), true);
printer.print("hello laundu");
printer.flush();
String ip123=socket.getInetAddress().toString();
printer.close();
BReader.close();
socket.close();
data += "Request of " + request
+ " from "+ ip123 + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(data);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
}
}
Client Code
mport android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
MainActivity activity;
OutputStream outputStream;
BufferedReader BReader;
String request;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse=textResponse;
this.activity=activity;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
Server server = new Server(socket);
server.start();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.print("futfujb");
out.flush();
/*
* notice: inputStream.read() will block if no data return
*/
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} /*finally {
if (socket != null) {
try {
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*/
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
private class Server extends Thread {
Socket socket;
Server(Socket socket)
{
this.socket=socket;
}
#Override
public void run() {
try { //Thread.sleep(500);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
if(inputStream.available()>0)
{
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
inputStream.close();
socket.close();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
As I commented above, there is nothing in this code that corresponds to either of these steps:
2.Server gets the request creates new SOCKET connection.
(a) There is no request, and (b) the server does not create a new connection. The client creates it. The server accepts it.
3.Server reads the data send by Client.
The client doesn't send any data.
There are two problems here (at least):
The server is blocking in readLine() waiting for a message that the client never sends. So it never gets to its own send, so nothing is received by the client. Have the client send a request, as per the comments.
The client is incorrectly using available(). Remove this test and let the client fall through into the read loop. It will exit that when the peer (the server) closes the connection.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
i have two application that i am trying to connect using sockets i am trying to test it but the problem is that it only works when i am using the same wifi connection on the phone. one phone has the client and the other on has the server. my question is how do i connect it when they not on the same wifi network
This is the client
package com.example.androidclient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonClear = (Button)findViewById(R.id.clear);
textResponse = (TextView)findViewById(R.id.response);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonClear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
textResponse.setText("");
}});
}
OnClickListener buttonConnectOnClickListener =
new OnClickListener(){
#Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(
editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
this i the severcode
package com.example.androidserversocket;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
infoip.setText(getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 3333;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
String msgReply = "Hello from Android, you are #" + cnt;
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();
message += "replayed: " + msgReply + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
i got the idea from this site
http://android-er.blogspot.com/2014/02/android-sercerclient-example-server.html
What you really have is communication between two components (activities in this case) the same device. I'm not sure if these two components are part of the same app or are installed separately but that does not matter as they will anyway not work across devices. Your server is simply a socket listener.
To implement device to device communication, you will need an actual server up and running outside of the device that the devices can communicate to (like maybe deploy it on your desktop while you are on wifi and let the devices find it or do the real deal and deploy it on a real server - may cost money). An example app for this can be found at https://github.com/Pirngruber/AndroidIM. The app is written for Android and uses Eclipse type builds but other than that the source code works well - I've used this in the past.
Or you can look into push messaging applications. tutorials for chat applications using Google Cloud messaging library are dime a dozen. While they do not use servers in the sense that we deploy applications, they use google's push system to send and receive messages.
I want to created simple Android bluetooth Client-Server program
Server Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
try {
mBluetoothServerSocket=mBluetoothAdapter.listenUsingRfcommWithServiceRecord(name,uUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket=mBluetoothServerSocket.accept();
mInputStream=mBluetoothSocket.getInputStream();
//if(mInputStream.available()>0){
mBufferedReader=new BufferedReader(new InputStreamReader(mInputStream));
data = mBufferedReader.readLine();
tv1.setText(data);
//}
if(mInputStream.available()>0){
data=mBufferedReader.readLine();
tv2.setText(data);
x++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Client Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lb=(Button)findViewById(R.id.button1);
btAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = btAdapter.getRemoteDevice(addressHTC);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btAdapter.cancelDiscovery();
btSocket.connect();
String message = "Hello.............. from....... Android......\n";
outStream = btSocket.getOutputStream();
byte[] msgBuffer = message.getBytes();
outStream.write(msgBuffer);
}
catch(IOException e){
e.printStackTrace();
}
lb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String m1="msg 2";
byte[] msgBuffer = m1.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
This application work in one side mode, just Send message to server and show received buffer, But i need to Send back some messages from server to client continuously.
How to do it?
if you have any idea. please share it.
This is works for me for contineously reading. Try it.
try {
BufferedReader Reader = new BufferedReader(
new InputStreamReader(mmSocket.getInputStream()));
while(true)
{
String receivedMsg;
while((receivedMsg = Reader.readLine()) != null)
{
// what you do with your message
}
}
} catch (Exception ex) {
System.out.println(ex);
}
you should have a different thread for listening which will send the message to the activity, this thread can be also the thread sending messages.
that way your the UI wont get stuck and you could receive messages continuously.
an example of such thread:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.util.Log;
public class MessageManager extends Thread {
private static final String TAG = "MessageListener thread";
private BluetoothSocket btConnectedSocket;
private InputStream inStream;
private OutputStream outStream;
private Activity parent;
private boolean run = true;
public MessageManager(BluetoothSocket btConnectedSocket, Activity parent) throws IOException {
this.btConnectedSocket = btConnectedSocket;
this.parent = parent;
inStream = btConnectedSocket.getInputStream();
outStream = btConnectedSocket.getOutputStream();
}
/* this method will listen continuously to messages received through the BT socket until you call cancel
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (run) {
try {
bytes = inStream.read(buffer);
}
catch(IOException ex) {
Log.e(TAG, "error while reading from bt socket");
}
parent.doStuffWithTheMessage(buffer); // pay attention: its in bytes. u need to convert it to a string
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) throws IOException{
outStream.write(bytes);
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
run = false;
try {
btConnectedSocket.close();
} catch (IOException e) { }
}
}
I am trying to implement code that can recognize different URL requests and perform different actions upon each request, for example, take picture by accessing http://192.168.0.120/pic , and send email by accessing via http://192.168.0.120/email
I already built the code for taking picture and sending email but not sure how to assign them to different URL requests?
I found one code that can run a web server to recognize only one IP address and i want to to modified it to recognize multiple IP addresses and perform different actions upon each request:
The Code:
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class Server extends Thread {
private ServerSocket listener = null;
private static Handler mHandler;
private boolean running = true;
public static LinkedList<Socket> clientList = new LinkedList<Socket>();
public Server(String ip, int port, Handler handler) throws IOException {
super();
mHandler = handler;
InetAddress ipadr = InetAddress.getByName(ip);
listener = new ServerSocket(port,0,ipadr);
}
private static void send(String s) {
Message msg = new Message();
Bundle b = new Bundle();
b.putString("msg", s);
msg.setData(b);
mHandler.sendMessage(msg);
}
#Override
public void run() {
while( running ) {
try {
Socket client = listener.accept();
new ServerHandler(client).start();
LockStatus.getInstance().setMyVar(true);
clientList.add(client);
} catch (IOException e) {
}
}
}
public void stopServer() {
running = false;
LockStatus.getInstance().setMyVar(false);
try {
listener.close();
} catch (IOException e) {
}
}
Thanks a lot
Here is the modification of the code, but still cannot recognize the IP address:
public void run() {
try {
serverSocket = new ServerSocket(SERVERPORT);
while (running) {
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
String line = null;
String IP = "192.168.0.111";
line = in.readLine();
if (line.equals(IP)) {
new ServerHandler(client).start();
LockStatus.getInstance().setMyVar(true);
Log.i(TAG, "IP Receive=" + line);
// Toast.makeText(getContext(), "Matches",
// Toast.LENGTH_SHORT).show();
} else {
Log.i(TAG, " IP not received :=" + line);
// Toast.makeText(getApplicationContext(), line +" != "+
// IP, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}