Server doesn't seem to receive Client message ANDROID - android

I am working on a chat client application and I have made a server. I managed to make the client connect to the server, but then when I send a message to the server, there's no reaction from the server.
Here is the part of the code of my server that is not working
class ClientConnect implements Runnable {
private DataInputStream in = null;
private DataOutputStream out = null;
Socket client;
ClientConnect(Socket client) {
try {
this.client = client;
/* obtain an input stream to this client ... */
in = new DataInputStream (client.getInputStream());
/* ... and an output stream to the same client */
setOut(new DataOutputStream (client.getOutputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
String msg, response;
ChatServerProtocol protocol = new ChatServerProtocol(this);
try {
while (true) {
if (in.available() > 0){
msg = in.readUTF();
response = protocol.process(msg);
getOut().writeBytes("SERVER: " + response);
}
}
} catch (IOException e) {
System.err.println(e);
} finally {
// The connection is closed for one reason or another
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendMsg(String msg) {
try {
getOut().writeBytes(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public DataOutputStream getOut() {
return out;
}
public void setOut(DataOutputStream out) {
this.out = out;
}
}
And here is the client :
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String response = null;
EditText nicknameField = (EditText)findViewById(R.id.nicknameField);
EditText passwordField = (EditText)findViewById(R.id.passwordField);
nickname = nicknameField.getText().toString();
password = passwordField.getText().toString();
switch(v.getId()){
case R.id.signin:
new SendMessage(this).execute("SIGNUP " + nickname + " " + password );
break;
case R.id.signup:
new SendMessage(this).execute("SIGNUP " + nickname + " " + password );
break;
}
}
private String onPostExecuteSendMessage() {
return null;
}
public void showMessage(String response) {
Builder builder = new AlertDialog.Builder(this);
builder.setMessage(response);
AlertDialog dialog = builder.create();
dialog.show();
}
public void getClientSocket(Socket client) {
this.client = client;
try {
out = new DataOutputStream (client.getOutputStream());
in = new DataInputStream (client.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public DataOutputStream getOut() {
// TODO Auto-generated method stub
return this.out;
}
public DataInputStream getIn() {
// TODO Auto-generated method stub
return this.in;
}
public void goMenuChat() {
// TODO Auto-generated method stub
Intent intent = new Intent(this, MenuChatActivity.class);
startActivity(intent);
}
}
Also I used an Asynctask to send message from the client :
package client.chatclient;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import android.os.AsyncTask;
public class SendMessage extends AsyncTask<String, String, String> {
private static final String msg_OK = "OK";
private static final String msg_NICK_IN_USE = "NICK IN USE";
private static final String msg_UNKNOWN_CMD = "UNKNOWN CMD";
private static final String msg_INVALID = "INVALID COMMAND";
private static final String msg_SEND_FAILED = "FAILED TO SEND";
private static final String msg_INCORRECT_IDS = "INCORRECT IDS";
private static final String msg_DISCONNECT = "DISCONNECT";
private WeakReference<MainActivity> activity;
private String message;
private String response = "";
private DataOutputStream out;
private DataInputStream in;
public SendMessage(MainActivity act){
super();
activity = new WeakReference<MainActivity>(act);
}
protected String doInBackground(String... message) {
this.message = message[0];
this.out = activity.get().getOut();
this.in = activity.get().getIn();
try {
out.writeBytes(this.message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response = convertStreamToString(this.in);
return response;
}
protected void onPostExecute(String response) {
if ((response == msg_INCORRECT_IDS) || (response == msg_NICK_IN_USE)){
activity.get().showMessage(response);
}
else if (response == msg_OK){
activity.get().goMenuChat();
}
}
private static String convertStreamToString(DataInputStream in) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the BufferedReader
* return null which means there's no more data to read. Each line will
* appended to a StringBuilder and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
I send my message from the client by clicking on a button then it goes to the SendMessage class, and send the message to the server and normally the server should receive my message in the loop "while (true)..." and sends back a response according to the protocol that I've implemented.
I really don't know what is wrong. If you know how to solve this issue or have some solutions, please tell me ! If you want more details, ask me ! :)
Thank you very much !
EDIT:
I instanciated my ClientConnect here
public class ChatServer {
private static int port = 8080;
public static void main (String[] args) throws IOException {
ServerSocket server = new ServerSocket(port); /* start listening on the port */
System.out.println( "Listening on "+ server );
Socket client = null;
while(true) {
try {
client = server.accept();
System.out.println( "Connection from " + client );
/* start a new thread to handle this client */
Thread t = new Thread(new ClientConnect(client));
t.start();
} catch (IOException e) {
System.err.println("Accept failed.");
System.err.println(e);
System.exit(1);
server.close();
}
}
}
}
EDIT: I found where the problem is. I put some log() statements as you said
log.d(null,"beforeconvert")
try {
log.d(null,"convert")
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
log.d(null,"errorconvert")
e.printStackTrace();
}
After that in logcat, it just shows "beforeconvert". I don't really know what the problem is ? while ((line = reader.readLine()) != null) is surely the problem. When I use the debugger step by step in eclipse, it stops at this line and doesn't even go inside the loop.
EDIT : I REALLY don't know why, but when I quit the emulator when running my app, it shows everything.
Listening on ServerSocket[addr=0.0.0.0/0.0.0.0,localport=8080]
Connection from Socket[addr=/127.0.0.1,port=56646,localport=8080]
client connected
msg received
error !
SIGNUP Nickname Password
SIGNUP Nickname Password
msg converted
OK
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at server.ClientConnect.convertStreamToString(ChatServer.java:357)
at server.ClientConnect.run(ChatServer.java:304)
at java.lang.Thread.run(Unknown Source)
java.net.SocketException: Connection reset by peer: socket write error

When you are writing data to output stream in the end you need to flush
this.out.flush();
I think this is why the data is not sent and received
Hope that helps.
Edit:
Let me try to explain in general idea..
When you are opening a socket you have a connection to another machince.
So the
in.available();
and
socket.accpet();
Should work.. once you are writing into outputstream you must flush in order to see the data(or close, i think it flushes before it get closed).
Anyway i attach a link to an example.. You should try this one, Or look at parts you have problem with..
http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/

Related

ESP8266 wifi server to android client

Ive been trying to setup a server using ESP8266 wifi module on a particular port. I'm done with that.
I want to receive the message from it now.
Whenever I connect using socket.connect(), I am able to detect it in the esp8266. But I cant receive any message, the server sends through the same socket.
I am trying to obtain the message using DataInputStream inside a while loop continuously in a async task.Pls let me know if my approach or code is wrong! Thanks!
This is my code:
package test.espclient;
import java.io.DataInputStream;
//import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear,buttonDiscon , buttonSendMsg;
EditText welcomeMsg;
Socket socket;
boolean socketStatus = false;
MyClientTask myClientTask;
#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);
buttonDiscon = (Button) findViewById(R.id.closeSocket);
buttonSendMsg = (Button) findViewById(R.id.sendMsg);
textResponse = (TextView) findViewById(R.id.response);
welcomeMsg = (EditText)findViewById(R.id.welcomemsg);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonDiscon.setOnClickListener(buttonDisconnectOnCLickListener);
//buttonSendMsg.setOnClickListener(sendMessage);
buttonClear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textResponse.setText("");
}
});
}
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
if(socketStatus)
Toast.makeText(MainActivity.this,"Already talking to a Socket!! Disconnect and try again!", Toast.LENGTH_LONG).show();
else {
socket = null;
String address = editTextAddress.getText().toString();
int port = Integer.parseInt(editTextPort.getText().toString());
String tMsg = welcomeMsg.getText().toString();
if (address == null || port == 0)
Toast.makeText(MainActivity.this, "Please enter valid address/port", Toast.LENGTH_LONG).show();
else {
myClientTask = new MyClientTask(address,port,tMsg);
myClientTask.execute();
} //else when no active socket conn. and credentials are validated.
} //else when already active socket conn.
}
};
OnClickListener buttonDisconnectOnCLickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!socketStatus)
Toast.makeText(MainActivity.this, "SOCKET Already Closed!!", Toast.LENGTH_SHORT).show();
else {
try {
onDisconnect();
if(myClientTask.isCancelled()) {
socket.close();
Toast.makeText(MainActivity.this, "Socket Closed!", Toast.LENGTH_SHORT).show();
socketStatus = false;
}
else
{
Toast.makeText(MainActivity.this, "Couldn't Disconnect! Pls try again!", Toast.LENGTH_SHORT).show();
socketStatus = true;
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
};
// OnClickListener sendMessage = new OnClickListener() {
// #Override
// public void onClick(View v) {
// String msg = welcomeMsg.toString();
// if(msg.equals(""))
// {
// Toast.makeText(MainActivity.this, "Message is empty!!!", Toast.LENGTH_SHORT).show();
// }
// else if(!socketStatus)
// {
// Toast.makeText(MainActivity.this, "Please Establish Socket Connection first!", Toast.LENGTH_SHORT).show();
// }
// else
// {
// MyClientTask myClientTask = new MyClientTask(editTextAddress
// .getText().toString(), Integer.parseInt(editTextPort
// .getText().toString()),
// msg);
// myClientTask.execute();
//
// }
//
// }
// };
public void onDisconnect()
{
myClientTask.cancel(true);
}
public class MyClientTask extends AsyncTask<Void, String, Void> {
String dstAddress;
int dstPort;
String response ="";
String msgToServer;
MyClientTask(String addr, int port, String msgTo) {
dstAddress = addr;
dstPort = port;
msgToServer = msgTo;
Log.w("MSG","Entering async task");
}
#Override
protected Void doInBackground(Void... arg0) {
// DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
socketStatus = true;
// dataOutputStream = new DataOutputStream(socket.getOutputStream());
// if(msgToServer != null){
// dataOutputStream.writeUTF(msgToServer);
// }
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
socketStatus = false;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
Log.w("MSG","Inside while loop for retrieving data");
while(!isCancelled()){
try {
dataInputStream = new DataInputStream(socket.getInputStream());
response = dataInputStream.readUTF();
if(!response.isEmpty())
{
publishProgress(response);
Log.w("Data:",response);
}
} catch (IOException e) {
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();
}
}
try {
Log.w("MSG","Stopping async task");
socket.close();
socketStatus = false;
} catch (IOException e) {
e.printStackTrace();
socketStatus = true;
}
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) {
Log.w("MSG","On postExecute method..");
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
UPDATE(16-12-15) I made the following changes under the doInBackground().
originally, I used DataInputStream, now I replaced it with BufferedReader.
The change was made under the while loop part for constantly checking the socket input stream. Also added the ESP8266 code for reference.
Now I able to Receive the text sent from ESP8266, but it reaches only after I send 3 or 4 messages via CIPSEND cmd. for e.g. if i send "hi", "hello" "yo", after sending the third word, I receive all the words together as "hihelloyo"
Instead of recieving each message as soon as it is sent, I receive it very late.
I am not sure what exactly is causing this problem. May be the buffer size?
How to solve this ?
MODIFIED CODE:
protected Void doInBackground(Void... arg0) {
// DataOutputStream dataOutputStream = null;
// DataInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
socketStatus = true;
// dataOutputStream = new DataOutputStream(socket.getOutputStream());
// if(msgToServer != null){
// dataOutputStream.writeUTF(msgToServer);
// }
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
socketStatus = false;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
Log.w("MSG","Inside while loop for retrieving data");
while(!isCancelled() && socketStatus) {
try {
// dataInputStream = new DataInputStream(socket.getInputStream());
// response = dataInputStream.readUTF();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
response = br.readLine();
if (!response.isEmpty()) {
publishProgress(response);
Log.w("Data:", response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
ESP266 code
#include <AltSoftSerial.h>
AltSoftSerial ESP8266 ;//(8,9)|Rx,Tx
int LED = 13;
boolean FAIL_8266 = false;
#define BUFFER_SIZE 128
char buffer[BUFFER_SIZE];
String ssid="\"SSID\"";
String pass="\"PASSWORD\"";
void clearESP8266SerialBuffer()
{
Serial.println("= clearESP8266SerialBuffer() =");
while (ESP8266.available() > 0) {
char a = ESP8266.read();
Serial.write(a);
}
Serial.println("==============================");
}
void sendHTTPResponse(int id, String content)
{
String response;
response = "HTTP/1.1 200 OK\r\n";
response += "Content-Type: text/html; charset=UTF-8\r\n";
response += "Content-Length: ";
response += content.length();
response += "\r\n";
response +="Connection: close\r\n\r\n";
response += content;
String cmd = "AT+CIPSEND=";
cmd += id;
cmd += ",";
cmd += response.length();
Serial.println("--- AT+CIPSEND ---");
sendESP8266Cmdln(cmd, 1000);
Serial.println("--- data ---");
sendESP8266Data(response, 1000);
}
boolean waitOKfromESP8266(int timeout)
{
do{
Serial.println("wait OK...");
delay(1000);
if(ESP8266.find("OK"))
{
return true;
}
}while((timeout--)>0);
return false;
}
//Send command to ESP8266, assume OK, no error check
//wait some time and display respond
void sendESP8266Cmdln(String cmd, int waitTime)
{
ESP8266.println(cmd);
delay(waitTime);
clearESP8266SerialBuffer();
}
//Basically same as sendESP8266Cmdln()
//But call ESP8266.print() instead of call ESP8266.println()
void sendESP8266Data(String data, int waitTime)
{
ESP8266.print(data);
delay(waitTime);
clearESP8266SerialBuffer();
}
void adc()
{
int ldr;
for(int i=0;i<=3;i++)
{
ldr = analogRead(A0);
sendESP8266Cmdln("AT+CIPSEND=0,5",1000);
sendESP8266Cmdln(String(ldr),1000);
delay(1000);
}
}
void setup()
{
Serial.begin(9600);
ESP8266.begin(9600);
pinMode(LED,OUTPUT);
do{
ESP8266.println("AT+RST");
delay(1000);
if(ESP8266.find("Ready"))
{
Serial.println("Module is ready");
delay(1000);
clearESP8266SerialBuffer();
sendESP8266Cmdln("AT+CWMODE=1",1000);
//Join Wifi network
sendESP8266Cmdln("AT+CWJAP="+ssid+","+pass,6500);
//Get and display my IP
sendESP8266Cmdln("AT+CIFSR", 1000);
//Set multi connections
sendESP8266Cmdln("AT+CIPMUX=1", 1000);
//Setup web server on port 80
sendESP8266Cmdln("AT+CIPSERVER=1,3333",1000);
Serial.println("Server setup finish");
FAIL_8266 = false;
}else{
Serial.println("Module have no response.");
delay(500);
FAIL_8266 = true;
}
}while(FAIL_8266);
digitalWrite(LED, HIGH);
ESP8266.setTimeout(1000);
}
void loop() {
// listen for communication from the ESP8266 and then write it to the serial monitor
if(ESP8266.available()) // check if the esp is sending a message
{
String msg = ESP8266.readString();
if(msg.substring(0,4)=="Link")
Serial.println("Client connected!");
else if(msg.substring(0,6)=="Unlink")
Serial.println("Client Disconncected!!");
else if(msg.substring(1,5)=="+IP")
{
Serial.println("Client says: "+msg.substring(9,14));
}
else
{
// Serial.println("Calling ADC.!");
//adc();
// Serial.println("Msg:"+msg.charAt(0)+msg.charAt(1)+msg.charAt(2)+msg.charAt(3));
// Serial.println("Something recieved!: "+msg.substring(1,2));
Serial.println("MSG:"+msg);
}
}
// listen for user input and send it to the ESP8266
if ( Serial.available() ) { ESP8266.write( Serial.read() ); }
}
//Clear and display Serial Buffer for ESP8266
UPDATE(17-12-15):Added pics for reference
My arduino serial window showing the AT+CIPSEND commands.
pic of the app running on phone.
As to this comment:
... it worked! I can get the messages immediately irrespective of their lengths, after i close the connection on esp side using cipclose=0. But is this is the only way? Is it possible to make the device and the app talk? How come it is possible in the telnet application, where i can continuously send data till i close connection on one side.?
On the upper application layers data from TCPIP connection is presented as a Stream. Using this stream with well-defined application protocols like HTTP or telnet, message exchange is defined. In your case basically Android side does not know what amount of data to receive. After using buffered reader you get buffered answer, not the whole.
In telnet protocol for example there are control commands. Thus the system goes on working.
To solve your case:
Close connection after every message. (this slows down things)
Implement a basic application protocol. For example: Implement a Message frame:
FRAME
1st byte : length ( this byte gives the length of the payload )
2nd...255th byte : payload ( this is the actual message )
LOGIC
-Sender packs the frame giving length and payload.
-Sender sends the data
...
-Receiver queries for the available bytes.
-When available bytes are >1 receive only 1 byte say it is 'n'
-'n' is the length of the total frame
-Read 'n' bytes from the stream. if EOF then return what is received.
In addition to this you can implement control commands.
For example you may want the receiver to close the connection so your frame can be:
Byte 1 : length
Byte 2 : command (0=nothing, 1=close conn)
Byte 3..n : payload
LOGIC
-When receiver finished receiving and command is 1 then closes the connection.

Android client getting all the inputStreamReader at the deco from the server

I'm asking for a little help here..
I made a Android app in order to get messages from a server. The app just have to show the server's messages and nothing else.
the thing is nothing is shown in the UI, all the messages are shown when I disconnect the server.
It's frustrating because the app get the data's, just don't show them before the disconnection of the server.
Here is my code :
public class SlimpleTextClientActivity extends Activity {
private TextView textView;
private Socket client;
private PrintWriter printwriter;
private BufferedReader bufferedReader;
//Following is the IP address of the chat server. You can change this IP address according to your configuration.
// I have localhost IP address for Android emulator.
private String CHAT_SERVER_IP = "192.168.2.2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slimple_text_client);
textView = (TextView) findViewById(R.id.textView1);
ChatOperator chatOperator = new ChatOperator();
chatOperator.execute();
}
/**
* This AsyncTask create the connection with the server and initialize the
* chat senders and receivers.
*/
private class ChatOperator extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
try {
client = new Socket(CHAT_SERVER_IP, 6666); // Creating the server socket.
if (client != null) {
printwriter = new PrintWriter(client.getOutputStream(), true);
InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
} else {
System.out.println("Server has not bean started on port 4444.");
}
} catch (UnknownHostException e) {
System.out.println("Faild to connect server " + CHAT_SERVER_IP);
e.printStackTrace();
} catch (IOException e) {
System.out.println("Faild to connect server " + CHAT_SERVER_IP);
e.printStackTrace();
}
return null;
}
/**
* Following method is executed at the end of doInBackground method.
*/
#Override
protected void onPostExecute(Void result) {
Receiver receiver = new Receiver(); // Initialize chat receiver AsyncTask.
receiver.execute();
}
}
/**
* This AsyncTask continuously reads the input buffer and show the chat
* message if a message is availble.
*/
private class Receiver extends AsyncTask<Void, Void, Void> {
private String message;
#Override
protected Void doInBackground(Void... params) {
while (true) {
try {
if (bufferedReader.ready()) {
message = bufferedReader.readLine();
publishProgress(null);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
}
}
#Override
protected void onProgressUpdate(Void... values) {
textView.append( message + "\n");
}
}
}
Hope that someone have an idea because here... I don't x)
Simon !
EDIT :
So... I went to java to test my code (simplification with the System.out.println)
Here is my code :
public class MainClass {
public static void main(String[] args) throws Exception {
final Socket client;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try{
client = new Socket("192.168.2.2", 6666);
InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
// create new buffered reader
br = new BufferedReader(inputStreamReader);
int value=0;
String monChar = null;
String maChaine = null;
//System.out.println(maChaine);
// reads to the end of the stream
while((value = br.read()) != -1)
{
// converts int to character
char c = (char) value;
maChaine = maChaine + c;
}
}catch(Exception e){
e.printStackTrace();
}finally{
// releases resources associated with the streams
if(is!=null)
is.close();
if(isr!=null)
isr.close();
if(br!=null)
br.close();
}
}
}
The thing is that I can't reach maChaine.
This does the same thing that before : I only can reach my String when the server is disconected.
If I put a "System.out.println(maChaine);" in my While it will print something at each rows and if I put it after it will only do something if the server is disconected.

Android Bluetooth Client Server Connection

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) { }
}
}

how to avoid an application hanging while calculating two functions together?

float totalKm = Contsants.jobEndKm-Contsants.jobStartKm ;
jcTotalKms.setText(String.format("%.2f",totalKm));
//jcTotalKms.setText(Float.toString((float) (totalKm/16.0)));
//finding total fare here
//int value=100;
if (totalKm<Contsants.minDist)
{
jcWaitingFare.setText("0");
float totalfare=Contsants.minFare;
jcTotalFare.setText(String.format("%.2f",(totalfare)));
Contsants.jobTotalKm= totalKm;
Contsants.jobTotalFare=totalfare;
}
else
{
jcWaitingFare.setText(Integer.toString((Contsants.cont_WaitingTimeInSec/60)*1));
float totalfare= Contsants.minFare+ ((totalKm-Contsants.minDist) *Contsants.rupeeKm) +(Contsants.cont_WaitingTimeInSec/60)*1;
jcTotalFare.setText(String.format("%.2f",(totalfare)));
Contsants.jobTotalKm= totalKm;
Contsants.jobTotalFare=totalfare;
}
tcpsocket class
public class tcpSocket extends Thread{
static boolean startSocket=false;
public static final String SERVERIP = "ip address here"; //your computer IP address
public static final int SERVERPORT = 8900;
private static boolean mRun = false;
public static Socket socket;
public static OnMessageReceived mMessageListener;
public static OnMessageReceived getmMessageListener() {
return mMessageListener;
}
public static void setmMessageListener(OnMessageReceived mMessageListener) {
tcpSocket.mMessageListener = mMessageListener;
}
public tcpSocket()
{
}
#Override
public void run(){
//some long operation
startSocket=true;
while(startSocket)
{
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.d("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
Log.d("TCP Client", "C: Sent.");
Log.d("TCP Client", "C: Done.");
final OutputStream out =socket.getOutputStream();
writeResponse(out, "$0001~01~"+Contsants.Cont_IMEINo+"~Version#");
//in this while the client listens for the messages sent by the server
final InputStream in = socket.getInputStream();
while(!mRun)
{
if (!(in.available() > 0)) {
goSleep(2000);
continue;
}
processClient(in);
}
}catch (Exception e) {
// TODO: handle exception
}finally{
socket.close();
}
} catch (Exception e) {
Log.d("tcp error",e.toString());
// TODO: handle exception
}
}
}
private void goSleep(final long milliSec) {
try {
Thread.sleep(milliSec);
} catch (final InterruptedException e) {
Log.e("server conn Thread ","Sleeping client interrupted" + e);
}
}
private void processClient(final InputStream in) throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
final char[] cbuf = new char[1024];
final int length = reader.read(cbuf);
if (length <= 0) {
Log.d("d","No data read from client.");
return;
}
cbuf[length] = '#';
String packet = new String(cbuf, 0, length + 1);
if (!packet.startsWith("$") && !packet.contains("#")) {
Log.d("d","Invalid packet recieved: " + packet);
return;
}
try
{
if(!packet.contains("$0002") && !packet.contains("$0423"))
{
final String [] packetDo=packet.split("\\~");
writeResponse(socket.getOutputStream(), "$102~"+packetDo[1]+"~"+Contsants.Cont_IMEINo+"#");
}
Log.d("d","Recived packet is :"+packet);
Message msg = new Message();
Bundle b = new Bundle();
b.putString("ServerMsg", packet);
msg.setData(b);
// send message to the handler with the current message handler
mHandler.sendMessage(msg);
}catch (Exception e) {
// TODO: handle exception
Log.e("TCP", "p: Error", e);
}
}
Handler mHandler =new Handler(){
#Override
public void handleMessage(Message message){
//update UI
Bundle b = message.getData();
final String data =b.getString("ServerMsg");
mMessageListener.messageReceived(data);
}
};
/*public class MyAsync extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
String response = null;
return SendMessage(response);
}
}
public static boolean SendMessage(final String response) {
OutputStream out;
try {
out = socket.getOutputStream();
writeResponse(out, response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mRun = true;
return false;
}
return true;
}
*/
public static boolean SendMessage(final String response)
{
OutputStream out;
try {
out = socket.getOutputStream();
writeResponse(out,response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mRun=true;
return false;
}
return true;
}
private static void writeResponse(final OutputStream out, final String response) throws IOException {
// logger.info("Sending response to client: " + response);
out.write(response.getBytes());
out.flush();
}
}
here is my code for calculating distance and fare together when the condition exceeds minimum(minDist) kilometer. But while checking this application in real device it hangs up after two kilometer. Because after two kilometer it goes to else condition part. i don't know how to solve this issue.

How recognize different URL requests to perform different actions using Android

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();
}
}

Categories

Resources