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

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.

Related

i want to read a data sent by the server(my server is an esp8266)

I have a server client connection and I am trying to read the messages sent by the server. I Can Send A Message To The Server, but when I try to read the messages in My App, I don't Know How To Read That Message.
My server Is An ESP8266 Module.
I Can send Message by this Module But I Dont Know How To Read That Message In Main3Activity.
This is the code I am using:
public class Main3Activity extends AppCompatActivity {
public static String data = " ";
Socket client;
SocketAddress socketAddress;
OutputStream outputStream;
String ServerIP = "192.168.1.1";
int ServerPort = 8888;
String message;
public final static String msg = null;
public int i;
EditText et_ServerIP, et_ServerPort;
TextView tv_DataSendRecive, info;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
tv_DataSendRecive = (TextView) findViewById(R.id.tv_DataSendRecive);
info = (TextView) findViewById(R.id.info);
et_ServerIP = (EditText) findViewById(R.id.et_ServerIP);
et_ServerPort = (EditText) findViewById(R.id.et_ServerPort);
}
public void onClick_btn_Send(View v) {
switch (v.getId()) {
case R.id.led_2:
message = "2 led\n";
break;
case R.id.led_1:
message = "1 led\n";
break;
case R.id.led_4:
message = "4 led\n";
break;
case R.id.led_3:
message = "3 led\n";
break;
case R.id.led_6:
message = "6 led\n";
break;
case R.id.led_5:
message = "5 led\n";
break;
case R.id.led_8:
message = "8 led\n";
break;
case R.id.led_7:
message = "7 led\n";
default:
return;
}
tv_DataSendRecive.append(" " + message);
new Thread(new Runnable() {
#Override
public void run() {
try {
ServerIP = et_ServerIP.getText().toString();
ServerPort = Integer.parseInt(et_ServerPort.getText().toString());
if (i == 0) {
socketAddress = new InetSocketAddress(ServerIP, ServerPort);
client = new Socket();
try {
client.connect(socketAddress);
} catch (IOException e1) {
e1.printStackTrace();
}
i = 1;
}
if (client.isConnected()) {
// ShowToast( "Client is Connected." );
try {
outputStream = client.getOutputStream();
} catch (IOException e1) {
e1.printStackTrace();
}
byte[] bytes = message.getBytes();
try {
outputStream.write(bytes);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
outputStream.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
///////// outputStream.close();\\\\\\\\\\\\\\\\\\\\\
} else {
ShowToast("Client is Not Connected.");
}
//////////////////// client.close(); \\\\\\\\\\\\\\\\\\\
} catch (final Exception e) {
ShowToast(e.toString());
}
}
}).start();
}
public void ShowToast(final String Data) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), Data, Toast.LENGTH_LONG).show();
}
});
}
}
And This Is my TCPClient class
public class TCPClient {
public static String SERVER_IP;
public static int SERVER_PORT;
private String mServerMessage; // message to send to the server
private OnMessageReceived mMessageListener = null; // sends message received notifications
private boolean mRun = false; // while this is true, the server will continue running
private PrintWriter mBufferOut; // used to send messages
public static BufferedReader mBufferIn; // used to read messages from the server
Socket socket;
public TCPClient(OnMessageReceived listener, String IP, String Port) {
mMessageListener = listener;
SERVER_IP = IP;
SERVER_PORT = Integer.parseInt(Port);
}
public void sendMessage(String message) {
if (socket == null || !socket.isConnected()) {
Log.e("313", "Socket Not Connected / Init !!!");
return;
}
if (mBufferOut != null && !mBufferOut.checkError()) {
mBufferOut.println(message);
mBufferOut.flush();
}
}
public void stopClient() {
mRun = false; //////////////////////mRun must be false///////////////////////////
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}
public void run() {
try {
// Creates a stream socket and connects it to the specified port number at the specified IP address
socket = new Socket(InetAddress.getByName(SERVER_IP), SERVER_PORT);
try {
// sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
// receives the message which the server sends back
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
mRun = true;
while (mRun) { // in this while the client listens for the messages sent by the server
mServerMessage = mBufferIn.readLine();
if (mServerMessage != null && mMessageListener != null) {
mMessageListener.messageReceived(mServerMessage); // call the method messageReceived from MyActivity class
}
}
} catch (Exception e) {} finally {
// the socket must be closed.
// It is not possible to reconnect to this socket, after it is closed,
// which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {}
}
public interface OnMessageReceived {
public void messageReceived(String message) throws IOException;
}
public boolean isConnected() {
if (socket == null) return false;
if (socket.isConnected()) return true;
else return false;
}
}

Android JsonWriter disconnecting clients from server socket

I have developed sample Android app for Socket communication over WiFi, with multiple clients. I am using JsonWriter for writing messages and JsonReader for reading messages.
When communicating one-to-one is no issue, but one-to-many is having some issues.
For Example:
My server S1 is connected with Client C1,C2 and C3, when the server try to send messages to all client at a same time the client C3 only receiving the messages but not others.
ServerSocketClass
public class ServiceMain extends Service implements OnResponseJsonWriter {
private boolean isRunning = false;
private MyThread myThread;
static final int SocketServerPORT = 8080;
ServerSocket serverSocket;
static List<ChatClient> userList;
static String msgLog = "";
private String TAG = ServiceMain.class.getSimpleName();
private boolean isServerAction = false;
private String TOKEN_REQUEST;
private Context mContext;
private JsonWriter writer = null;
private JSON_Writer jsonWriter;
private DataInputStream dataInputStream = null;
private DataOutputStream dataOutputStream = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mContext = ServiceMain.this;
userList = new ArrayList<ChatClient>();
myThread = new MyThread();
}
#SuppressWarnings("deprecation")
#Override
public synchronized void onDestroy() {
try {
if (isRunning) {
myThread.interrupt();
myThread.stop();
}
} catch (UnsupportedOperationException e) {
}
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!isRunning) {
myThread.start();
isRunning = true;
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onJsonWriterRespnse(boolean isSuccess) {
try {
writer.flush();
dataOutputStream.flush();
} catch (Exception e) {
Log.e(TAG, "onJsonWriterRespnse " + e);
}
}
class MyThread extends Thread {
static final long DELAY = 3000;
#Override
public void run() {
while (isRunning) {
try {
ChatServerThread chatServerThread = new ChatServerThread();
chatServerThread.start();
Thread.sleep(DELAY);
} catch (InterruptedException e) {
isRunning = false;
}
}
}
}
private class ChatServerThread extends Thread {
#Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
while (true) {
socket = serverSocket.accept();
ChatClient client = new ChatClient();
userList.add(client);
ConnectThread connectThread = new ConnectThread(client, socket);
connectThread.start();
}
} catch (IOException e) {
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class ChatClient {
String id;
Socket socket;
ConnectThread chatThread;
#Override
public String toString() {
return socket.getInetAddress().getHostAddress();
}
}
private class ConnectThread extends Thread {
Socket socket;
ChatClient connectClient;
String msgToSend = "";
ConnectThread(ChatClient client, Socket socket) {
connectClient = client;
this.socket = socket;
client.socket = socket;
client.chatThread = this;
}
#Override
public void run() {
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
String n = dataInputStream.readUTF();
connectClient.id = n;
socketConnectionResponse(connectClient, connectClient.id);
while (true) {
if (dataInputStream.available() > 0) {
}
isServerAction = false;
if (!msgToSend.equals("")) {
TeacherAttention attentionModel;
switch (msgToSend) {
case Constants.LOOK_AT_ME:
isServerAction = true;
TOKEN_REQUEST = Constants.LOOK_AT_ME;
msgToSend = "";
attentionModel = new TeacherAttention(Constants.TEACHER_ATTENTION_REQUEST,
Constants.RESPONSE_SUCCESS, Constants.LOOK_AT_ME);
writer = new JsonWriter(new OutputStreamWriter(dataOutputStream, "UTF-8"));
writer.setIndent(" ");
// for write JSON
jsonWriter = new JSON_Writer(mContext, writer, attentionModel, "");
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.e("TAG", "finally??");
userList.remove(connectClient);
}
}
private void sendMsg(String msg) {
msgToSend = msg;
}
}
public static void broadcastMsgToAll(String msg) {
for (int i = 0; i < userList.size(); i++) {
userList.get(i).chatThread.sendMsg(msg);
}
}
/**
* send response to single user
*
* #param client
* #param userid
*/
public void socketConnectionResponse(ChatClient client, String userid) {
if (client != null) {
client.chatThread.sendMsg(userid);
} else {
Toast.makeText(ServiceMain.this, "No user connected", Toast.LENGTH_LONG).show();
}
}
}
ClientSocketClass:
public class ClientSocketService extends Service implements OnResponseJsonWriter,
OnResponseJsonReader {
private static String TAG = ClientSocketService.class.getSimpleName();
static final int socketServerPORT = 8080;
private ChatClientThread chatClientThread = null;
static String msgToSend = "";
static boolean goOut = false, isSocketRunning = false;
private JsonReader reader;
private Context mContext;
private DataOutputStream dataOutputStream = null;
private DataInputStream dataInputStream = null;
private JsonWriter writer = null;
private JSON_Reader jsonReader;
private JSON_Writer jsonWriter;
public static Socket socket = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
db = new DatabaseHelper(this);
getAllStudent = new ArrayList<>();
mContext = ClientSocketService.this;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
chatClientThread = new ChatClientThread(getUserID(), getTeacherIP(), socketServerPORT);
chatClientThread.start();
return super.onStartCommand(intent, flags, startId);
}
private class ChatClientThread extends Thread {
String name;
String dstAddress;
int dstPort;
ChatClientThread(String name, String address, int port) {
this.name = name;
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(name);
dataOutputStream.flush();
while (!goOut) {
if (dataInputStream.available() > 0) {
reader = new JsonReader(new InputStreamReader(dataInputStream, "UTF-8"));
try {
jsonReader = new JSON_Reader(mContext, reader);
} catch (Exception e) {
Log.e(TAG, "dataInputStream" + e);
} finally {
}
}
}
isSocketRunning = true;
}
} catch (UnknownHostException e) {
final String eString = e.toString();
Log.e("eString 1", "eString " + eString);
isSocketRunning = false;
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
Log.e("eString 2", "eString " + eString);
isSocketRunning = false;
} finally {
if (socket != null) {
try {
isSocketRunning = false;
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void sendMsg(String msg) {
msgToSend = msg;
}
private void disconnect() {
goOut = true;
}
public static boolean isSocketRunning() {
return isSocketRunning;
}
#Override
public void onJsonWriterRespnse(boolean isSuccess) {
try {
writer.flush();
dataOutputStream.flush();
} catch (IOException e) {
Log.e(TAG, "onJsonWriterRespnse " + e);
isSocketRunning = false;
}
}
#Override
public void onSocketReaderResponse(String requestToken, final ArrayList<SocketResponseModel> socketResponse) {
}
#Override
public void onSocketResponseUpdateIP(SocketResponseUpdateIp responsIp) {
}
#Override
public void onTeacherAttention(TeacherAttention teacherAttention) {
Intent lookIntent;
switch (teacherAttention.getTokenStatus()) {
case Constants.LOOK_AT_ME:
lookIntent = new Intent(this, LookAtMeActivity.class);
lookIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(lookIntent);
break;
}
}

Android 6.0 cant create socket

I cant create a simple TCP connection to my server.
I created a AsyncTask to send messages, but it didn't work.
I added INTERNET and ACCESS_NETWORK_STATE to the permissions.
I don't know what else to try.
public class ServerCommunicator extends AsyncTask<String,Void,Void>{
public static String SERVER_IP = "192.168.2.148";
public static int SERVER_PORT = 1337;
public static String SERVER_PW = "adsfadsf";
public Context context;
#Override
protected Void doInBackground(String... params) {
//Create Command
CommandFactory cmdFactory = new CommandFactory();
Command cmd = cmdFactory.createCommand();
System.out.println("Cmd created..");
//-----
try {
System.out.println(SERVER_IP);
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
System.out.println("Created serverAddr "+ SERVER_IP);
Socket socket = new Socket(serverAddr,SERVER_PORT);
System.out.println("Socket created..");
//sends the message to the server
PrintWriter mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
String msg2Send = Crypter.Encrypt(cmd.toString(), SERVER_PW);
sendMsgAsByteArr(socket, msg2Send);
Command recCmd = cmdFactory.extractCommandFromStr(receiveMsg(socket));
socket.close();
Toast.makeText(context, recCmd.id, Toast.LENGTH_LONG).show();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static void sendMsgAsByteArr(Socket socket, String msg) {
try {
socket.getOutputStream().write(msg.getBytes());
System.out.println("sent cmd..");
} catch (IOException e) {
e.printStackTrace();
}
}
private static String receiveMsg(Socket socket) {
String msg = "";
int c;
ArrayList<Byte> incoming = new ArrayList<Byte>();
try {
while((c = socket.getInputStream().read())!=-1) {
incoming.add((byte)c);
}
byte[] allBytes = new byte[incoming.size()];
for(int i = 0; i < incoming.size(); i++) {
allBytes[i] = incoming.get(i);
}
msg = new String(allBytes);
} catch (IOException e) {
e.printStackTrace();
}
return msg;
}
}
My program runs till Socket socket = new Socket(serverAddr, SERVER_PORT); then it stops. It doesn't show any stack trace or errors.
Any ideas?
I debugged your code, and while there were multiple issues, none were related to Android 6.
I created a simplified version of your code and got it working.
One issue is that your context reference was null, so I set it in the constructor.
Another issue is that you were trying to show a Toast on a background thread, which won't work.
Another issue was your send and receive methods, they didn't work for me.
Here's the simplified code that I got working with a TCP/IP server, tested on both Android 4.4.4 and Android 6.
You can take this and expand on it as needed:
public class ServerCommunicator extends AsyncTask<String,Void,String> {
public static String SERVER_IP = "11.222.33.444";
public static int SERVER_PORT = 1234;
public Context context;
public ServerCommunicator(Context c) {
this.context = c;
}
#Override
protected String doInBackground(String... params) {
try {
System.out.println(SERVER_IP);
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
System.out.println("Created serverAddr "+ SERVER_IP);
Socket socket = new Socket(serverAddr,SERVER_PORT);
System.out.println("Socket created..");
//sends the message to the server
PrintWriter mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
String msg2Send = "{\"HelloWorld\", \"1234\"}";
mBufferOut.println(msg2Send);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String result = in.readLine();
System.out.println("result: " + result);
socket.close();
return result;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
}

Socket client - server(android)

Sorry for my english. I am trying to create client and server. Now, my logic is like this:
I start app -> start server -> server listening to all messages -> if client sends message to server -> message goes to server -> message received by server -> server needs to send a message to all its customers.
But the server does not do this
** the server needs to send a message to all its customers**
or maybe
the client is not listening to the server.
my question: Why does the client not accept messages from the server?
//Main
//send message
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sendText.getText().toString().equals("")) {
return;
}
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg(sendText.getText().toString() + "\n");
}
});
//method create server and client, cliend connect to server
createServer(port);
}
public void createServer(int port) {
//create server
ChatServerThread chatServerThread = new ChatServerThread(port);
chatServerThread.start();
//subscribe to server 192.168.31.101 - ip server
createClient("Testov", "192.168.31.101", port);
}
//method for create client
public void createClient(String name, String ipAdress, int SocketServerPORT) {
chatClientThread = new ChatClientThread(
name, ipAdress, SocketServerPORT);
chatClientThread.start();
}
//this is server class
private class ChatServerThread extends Thread {
int SocketServerPORT;
public ChatServerThread(int SocketServerPORT) {
//set port
this.SocketServerPORT = SocketServerPORT;
}
#Override
public void run() {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
//create server socket
serverSocket = new ServerSocket(SocketServerPORT);
//waite connect
socket = serverSocket.accept();
Log.e("connect", "server side");
//for input and output
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
//listener
while(true) {
if (dataInputStream.available() > 0) {
//read line
String newMsg = dataInputStream.readUTF();
//send line to client
dataOutputStream.writeUTF(newMsg);
final String ms = newMsg;
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), ms, Toast.LENGTH_SHORT).show();
}
});
//end thread
dataOutputStream.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//this is client side
private class ChatClientThread extends Thread {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
String name;
String dstAddress;
int dstPort;
String msgToSend = "";
boolean goOut = false;
String msgLog = "";
ChatClientThread(String name, String address, int port) {
this.name = name;
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
try {
//set ip adress and port
socket = new Socket(dstAddress, dstPort);
//for get and post data
String mesageFromServer = null;
dataInputStream = new DataInputStream(socket.getInputStream());
while(!goOut) {
//wait message from server
mesageFromServer = dataInputStream.readUTF();
//output
Log.e("client", mesageFromServer);
final String ms = mesageFromServer;
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), ms, Toast.LENGTH_SHORT).show();
}
});
msgToSend = "";
}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
Log.e("errror", eString);
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
Log.e("errror", eString);
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void sendMsg(String msg){
try {
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
private void disconnect(){
goOut = true;
}
}

Why DataOutputStream loses a character?

I have a simple connection activity:
package com.example.conn08;
import ...;
public class MainActivity extends Activity
{
public static Socket clientSocket;
public static DataOutputStream outToServer;
public static PrintWriter outTest;
public static BufferedReader inToServer;
With PrintWriter outTest I test server's availability:
If the user has no Internet, or the server doesn't work, I put Thread on a pause with Boolean shouldContinue.
private Thread mThread;
private final Object lock = new Object();
private Boolean shouldContinue = true;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mThread = new Thread(new Runnable()
{
public void run()
{
while (true)
{
synchronized(lock)
{
try
{
lock.wait(); // lock the Thread
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
while (shouldContinue)
{
try
{
final String data = inToServer.readLine();
if (data != null)
{
Log.v("data", data);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
String put[] = data.split("#");
//Data parsing
}
});
}
}
catch (IOException e)
{
e.printStackTrace();
}
Check on availability of the server:
try {
if(clientSocket.getInputStream().read() == -1)
{
Log.v("Connection: ", "lost");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
mThread.start();
Connect();
}
public void Connect()
{
shouldContinue = true;
try
{
clientSocket = new Socket();
clientSocket.connect(new InetSocketAddress("localhost", 15780), 30000);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
inToServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
outTest = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(clientSocket.getOutputStream())), true);
synchronized(lock)
{
lock.notify();
}
sendUTF("3#kokoko"); //send the message!
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void sendUTF(String str)
{
try
{
byte[] buf = str.getBytes("UTF-8");
outToServer.write(buf, 0, buf.length);
outToServer.writeBytes("\n");
outToServer.flush();
}
catch (IOException e)
{
e.printStackTrace();
outServ.setText("Нет соединения!");
}
}
}
Problem in that when I don't use the
if(clientSocket.getInputStream().read() == -1)
And send data to server like here:
sendUTF("3#kokoko");
All is fine, but if I use it, on server I see this message like
"#kokoko" - I lose the first character of the message and my socket is crushed! Help me please

Categories

Resources