Android Socket does not send data - java

I'm trying to send a string to a server over TCP using socket and AsyncTask.
String will change with the ON/OFF status of the button.
I have no error but data wont go out and I get no answer from the server.
Could someone help me to understand what I'm doing wrong ?
Part of MyActivity code (interesting section comes after //Create an instance of AsyncTask):
final MySerDeser msg = new MySerDeser();
switch (tab_ID) {
case 1:
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
//----- btn_BotolaUp
final ToggleButton btn_BotolaUp = (ToggleButton) rootView.findViewById(R.id.btn_BotolaSu);
btn_BotolaUp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String toastmessage;
if (isChecked) {
msg.serialize("datafield1", "datafield2", "datafield3", "1");
toastmessage = "Chiusura botola start";
} else {
msg.serialize("datafield1", "datafield2", "datafield3", "0");
toastmessage = "Chiusura botola stop";
}
//Create an instance of AsyncTask
ClientAsyncTask clientAST = new ClientAsyncTask();
Log.d("NetStuff" , "ClientAsyncTask");
//Pass the server ip, port and client message to the AsyncTask
clientAST.execute(new String[] { "192.168.1.100", "10000",msg.serialized });
Log.d("NetStuff", "clientAST.execute(new String[]...");
Toast.makeText(rootView.getContext(), toastmessage, Toast.LENGTH_SHORT).show();
}
});
The AsyncTask code:
/**
* AsyncTask which handles the communication with the server
*/
class ClientAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = null;
Log.d("NetStuff" , "String doInBackground");
try {
//Create a client socket and define internet address and the port of the server
Socket socket = new Socket(params[0],
Integer.parseInt(params[1]));
Log.d("NetStuff" , "Socket socket = new Socket");
//Get the input stream of the client socket
InputStream is = socket.getInputStream();
Log.d("NetStuff" , "InputStream is = socket.getInputStream");
//Get the output stream of the client socket
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
Log.d("NetStuff" , "PrintWriter out = new PrintWriter");
//Write data to the output stream of the client socket
out.print(params[2]);
Log.d("NetStuff", "out.print(" + params[2] + ")");
//Buffer the data coming from the input stream
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
Log.d("NetStuff" , "BufferedReader br = new BufferedReader");
//Read data in the input buffer
result = br.readLine();
Log.d("NetStuff" , "result = br.readLine()");
//Close the client socket
socket.close();
Log.d("NetStuff", "socket.close");
} catch (NumberFormatException e) {
Log.d("NetStuff", "NumberFormatException");
e.printStackTrace();
} catch (UnknownHostException e) {
Log.d("NetStuff", "UnknownHostException");
e.printStackTrace();
} catch (IOException e) {
Log.d("NetStuff", "IOException");
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
//Write server message to the text view
Log.d("NetStuff","Server answer:" + s);
}
}
Logcat is the following:
01-06 08:58:32.743 31685-31685/com.dev.netmanagement D/NetStuff: ClientAsyncTask
01-06 08:58:32.743 31685-31685/com.dev.netmanagement D/NetStuff: clientAST.execute(new String[]...
01-06 08:58:32.743 31685-31742/com.dev.netmanagement D/NetStuff: String doInBackground
01-06 08:58:32.753 31685-31742/com.dev.netmanagement D/NetStuff: Socket socket = new Socket
01-06 08:58:32.753 31685-31742/com.dev.netmanagement D/NetStuff: InputStream is = socket.getInputStream
01-06 08:58:32.763 31685-31742/com.dev.netmanagement D/NetStuff: PrintWriter out = new PrintWriter
01-06 08:58:32.773 31685-31742/com.dev.netmanagement D/NetStuff: out.print(datafield1,datafield2,datafield3,1)
01-06 08:58:32.773 31685-31742/com.dev.netmanagement D/NetStuff: BufferedReader br = new BufferedReader
Looking with wireshark, I see that no data are going out..
Looking # logcat, it's clear that task is waiting an answer from the server.
The answer will never arrive because the server has no question to answer...
Commenting following code:
//Buffer the data coming from the input stream
/*BufferedReader br = new BufferedReader(
new InputStreamReader(is));
Log.d("NetStuff" , "BufferedReader br = new BufferedReader");
//Read data in the input buffer
result = br.readLine();
Log.d("NetStuff" , "result = br.readLine()");
*/
//Close the client socket
socket.close();
Log.d("NetStuff", "socket.close");
The task end and socket is closed (but still no one TCP string out from the ethernet).
Why my awful code is not transmitting ? [Help]

[SOLVED]
Thanks to greenapps, I add out.flush() and all is now working.
So, if you need to send TCP data declare following class:
/**
* AsyncTask which handles the communication with the server
*/
class ClientAsyncTask extends AsyncTask<String, Void, String> {
#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 socket = new Socket(params[0],
Integer.parseInt(params[1]));
//Get the input stream of the client socket
InputStream is = socket.getInputStream();
//Get the output stream of the client socket
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
//Write data to the output stream of the client socket
out.print(params[2]);
out.flush();
//Buffer the data coming from the input stream
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
//Read data in the input buffer
result = br.readLine();
//Close the client socket
socket.close();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
//Write server message to the text view
Log.d("NetStuff","Server answer:" + s);
}
}
And call task with:
//Create an instance of AsyncTask
ClientAsyncTask clientAST = new ClientAsyncTask();
//Pass the server ip, port and client message to the AsyncTask
clientAST.execute(new String[]{"192.168.1.100", "10000", "message to send"});
Great !

Related

Java Client not receiving C# Server response TCP

Can somebody explain to me what I am doing wrong.First time I try to implement TCP between Java and C#:
Sever code c#
`
public void CreateServer()
{
Thread thread = new Thread(() =>
{
IPAddress addr = IPAddress.Parse(localIP);
tcpListener = new TcpListener(addr, 5053);
if (tcpListener != null)
{
tcpListener.Start();
while (!end)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
var ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
Console.WriteLine("Client connected from "+ip);
NetworkStream clientStream = tcpClient.GetStream();
StreamReader reader = new StreamReader(clientStream, Encoding.UTF8);
try
{
string request = reader.ReadToEnd();
Console.WriteLine("Message from client: " + request);
Byte[] StringToSend = Encoding.UTF8.GetBytes("Server");
clientStream.Write(StringToSend, 0, StringToSend.Length);
Console.WriteLine("Sending response back");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
});
thread.Start();
}
`
Client code java
`
public class TCP {
private String IP;
private InetAddress server;
private Socket socket;
public TCP(String IP) {
this.IP = IP;
}
protected void runTCP() {
try {
server = InetAddress.getByName(IP);
socket = new Socket(server, 5053);
System.out.println("Client connected. Listening on port 5053");
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMessage(String message) {
try {
System.out.println("Sending data...");
if (socket.isClosed()) socket = new Socket(server, 5053);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.print(message);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void getResponseServer() {
Thread thread = new Thread() {
#Override
public void run() {
try {
System.out.println("Attempting to get response...");
if (socket.isClosed()) socket = new Socket(server, 5053);
BufferedReader mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String mServerMessage = mBufferIn.readLine();
System.out.println("Server message: " + mServerMessage);
} catch (Exception e) {e.printStackTrace();}
}
};
thread.start();
}
}
`
Output on server I get when sending "Hello" from client to server:
Client connected from 192.16.... Message from client: Hello Sending response back Client connected from 192.16....
Output on client:
Client connected. Listening on port 5053 Sending data... Attempting to get response...
Never gets response... Why?
Tried researching but found nothing yet, tried other code but didnt work aswell...
sorry , I can't comment. maybe you can use telnet command to vertify c# code is corrent.
telnet ip port
first, locate problem, then solve it.
if server is ok , we can use nc command vertify client code, I have test your java code , except every send data will close socket , other is ok.
Fixed it by removing writer.close() cause that causes socket closing and makes another connection to the server by creating again the socket which makes the server wait for a stream of data and the client wait for a response...
System.out.println("Sending data...");
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
writer.println(message);
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

I Can't read from the server-side socket

First of all, the android application will connect to the server (PC).
Then the android will send a message.
And finally the android application should receive a message from the server.
When I send the message from the android to the Server, everything goes well.
However, when it comes to reading from socket inside the android app, I can't receive anything.
Here is the Server code
ServerSocket Sock = new ServerSocket(7777);
System.out.println("Waiting for connection...\n");
Socket connectionSocket = Sock.accept();
System.out.println("Client In...");
BufferedReader inFromClint = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter printwriter = new PrintWriter(connectionSocket.getOutputStream());
String txt = inFromClint.readLine();
System.out.println(txt);
String MsgToClient = "{\"LoginFlag\":\"N\"}"; //{"LoginFlag":"P"}
printwriter.write(MsgToClient);
printwriter.flush();
printwriter.close();
System.out.println("\nMsg Sent");
Sock.close();
And this is sample of the Android app:
new Thread(new Runnable() {
#Override
public void run() {
try
{
BufferedReader bufferedReader = null;
PrintWriter printwriter = null;
port = 7777;
client = new Socket("192.168.1.2", port);
printwriter = new PrintWriter(client.getOutputStream());
printwriter.write(SMsgLog);
printwriter.flush();
printwriter.close();
bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
if( bufferedReader.ready() )
{
RJasonLog = bufferedReader.readLine(); //rcv as jason
}
else
{
RJasonLog = null;
}
if (RJasonLog != null)
{
JSONObject objectRcv = new JSONObject(RJasonLog);
if (objectRcv != null)
{
RMsgLog = objectRcv.getString("LoginFlag"); //Jason Key from the server
}
}
RMsgLog = "N";
if(RMsgLog.equals("N"))
{
alert.showAlertDialog(Login.this, "Login failed..", "Username/Password is incorrect", false);
}
else
alert.showAlertDialog(Login.this, "Login failed..", "Please Try Again", false);
client.close();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
The clienr is trying to read a line. But the server is not sending a line with printwriter.write(MsgToClient);. Change to printwriter.write(MsgToClient + "\n"); to send a line.
I solved it with the help from the comments.
I removed printwriter.close(); on client side.
And then I added \n In both client and server before sending the message
Don't close the output stream in client code, Remove this line:
printwriter.close();
Stream should not be closed until connection is alive. It should be closed at the end when you are done with the socket. Closing connection will also close the streams associated with it.
Here is small description about the getOutputStream method.
getOutputStream
public OutputStream getOutputStream() throws IOException Returns an
output stream for this socket. If this socket has an associated
channel then the resulting output stream delegates all of its
operations to the channel. If the channel is in non-blocking mode then
the output > stream's write operations will throw an
IllegalBlockingModeException.
Closing the returned OutputStream will close the associated socket.
Returns: an output stream for writing bytes to this socket. Throws:
IOException - if an I/O error occurs when creating the output stream
or if the socket is not connected.

sending and recieving data through sockets in the same activity

i'm using TCP socket to send and receive data from the same socket in the same activity through client server thread, the purpose of that is to send a string to other device and that string will trigger a notification once the other device receives it then that device will replay with something like dismiss or accepted, the problem that i'm having is after sending the string the other device receives it and send the dismiss or accepted String but my divice doesn't receive that string i guess there is a problem in my ServerThread be aware that the server thread and client thread are in the same activity used as an inner classes and get called in a button.
code:
ClientThread
private class ChatClientThread extends Thread {
#Override
public void run() {
Socket socket = null;
DataOutputStream dataOutputStream = null;
try {
socket = new Socket("192.168.0.113", 23);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataOutputStream.writeUTF(" "+"SolveProblemOrder_2");
dataOutputStream.flush();
ServerThread serv =new ServerThread();
serv.start();
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
TicketDetails.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TicketDetails.this, eString, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
TicketDetails.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TicketDetails.this, eString, Toast.LENGTH_LONG).show();
}
});
} 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();
}
}
TicketDetails.this.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
}
}
ServerThread
public class ServerThread extends Thread {
private ServerSocket serverSocket;
private Socket clientSocket;
public void run(){
try{
// Open a server socket listening on port 23
InetAddress addr = InetAddress.getByName(getLocalIpAddress());
serverSocket = new ServerSocket(23, 0,addr);
try{
clientSocket = serverSocket.accept();
DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
String newMsg = null;
Toast.makeText(getApplicationContext(), newMsg, Toast.LENGTH_LONG).show();
// Client established connection.
// Create input and output streams
while (true) {
if (dataInputStream.available() > 0) {
newMsg = dataInputStream.readUTF();
}
}}catch(Exception e){
e.printStackTrace();
}
// Perform cleanup
} catch(Exception e) {
// Omitting exception handling for clarity
}
}
private String getLocalIpAddress() throws Exception {
String resultIpv6 = "";
String resultIpv4 = "";
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if(!inetAddress.isLoopbackAddress()){
if (inetAddress instanceof Inet4Address) {
resultIpv4 = inetAddress.getHostAddress().toString();
} else if (inetAddress instanceof Inet6Address) {
resultIpv6 = inetAddress.getHostAddress().toString();
}
}
}
}
return ((resultIpv4.length() > 0) ? resultIpv4 : resultIpv6);
}
}
i start those two threads in a button Click listener:
ChatClientThread chatClient=new ChatClientThread();
chatClient.start();
ServerThread serv =new ServerThread();
serv.start();
if this won't work using server/client in the same activity using the same port is there any other way to listen to a socket like is there a built in listener or something like that.
any help is appreciated
You write to socket thru socket.getOutputStream() and you must read from InputStream of socket.getInputStream() ;
You can adapt your code .
Your server use InputStream from socket to read data ,so you must to do also in your client code , cause you want also to receive data not only to send.
check this out just read is is very simple.
https://systembash.com/a-simple-java-tcp-server-and-tcp-client/
See the code for reading from socket taht start with :
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
and code for writing to socket:
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
or search google : java client server .
The ideea is that you send data to the socket outputstream and you can read it from same socket inputstream.
you see here example it read data from socket input and send data thru socket output , to server
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();

Android Client Implementation Errors

Trying To let an android device get data from a server I have:
RetreiveFeedTask DoStuff=new RetreiveFeedTask();
try{
Work=(DoStuff.execute(Exec)).get();
}
catch(Exception e)
{System.out.print(e+"");}
Async Implementation:
class RetreiveFeedTask extends AsyncTask<String , Void , String> {
//private Exception e;
String GotBack="empty";
#Override
protected String doInBackground(String... params) {
try{
Socket socket = new Socket("192.168.1.66", 2727);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
BufferedReader input=new BufferedReader(new InputStreamReader(socket.getInputStream()));
output.println(params[0]);
output.flush();
output.close();
GotBack="OverWritten";
GotBack=input.readLine();
socket.close();
}
catch(Exception e){System.out.print(e+"");}
return GotBack;
}
}
My server is sending the ACK:
"1\n"
But what I get on the screen is "Overwritten" which is the value before I read data from the server.
Any idea why?
Update
I was closing the output socket so it was throwing an exception. Now Im not getting errors but the value I get is empty. Any idea why?
New Code:
class RetreiveFeedTask extends AsyncTask<String , Void , String> {
//private Exception e;
String GotBack="empty";
#Override
protected String doInBackground(String... params) {
try{
Socket socket = new Socket("192.168.1.66", 2727);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
BufferedReader input=new BufferedReader(new InputStreamReader(socket.getInputStream()));
output.println(params[0]);
output.flush();
String read="";
while((read=input.readLine())!=null)
{
GotBack+=read;
}
output.close();
socket.close();
}
catch(Exception e){Log.e("MyApp","exception",e);}
return GotBack;
}
}
Yes. Executing input.readLine(); must have thrown an exception which you handled and printed. The value of GotBack is now "OverWritten" which is returned on return GotBack;.

Android:socket communication

I am trying to create simple app with android client and java server
android client is able to send message to server(java)
while when i try to read server reply
error:socket closed.
line(if((receiveMessage = receiveRead.readLine()) != null) )
public class ClientConnectorTask extends AsyncTask<String, Void, Integer> {
private Socket client;
private PrintWriter printwriter;
protected Integer doInBackground(String...strings) {
// validate input parameters
if (strings.length <= 0) {
return 0;
}
// connect to the server and send the message
try {
client = new Socket("192.168.1.4", 7777);
printwriter = new PrintWriter(client.getOutputStream(),true);
//while(true){
InputStream istream = client.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
String receiveMessage;
while (true){
// printwriter.write(strings[0]);
printwriter.print(strings[0]);
printwriter.flush();
printwriter.close();
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
}
}
//}
//client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
protected void onPostExecute(Long result) {
return;
}
}
Closing the PrintWriter inside the loop doesn't make sense, and closing it before the readLine() call doesn't make sense either. Closing either the input or the output stream of a Socket closes the other stream and the socket.

Categories