I'm making an app that sends a string to a server over a socket and then reads the output after the server has processed that data. It worked perfectly when it was my foreground task, but I have since used AsyncTask to show a process dialog while the socket communication runs in the background, and things start breaking after I read the output from the server and then try to close the socket.
private class Progressor extends AsyncTask<String, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(ClearTalkInputActivity.this, "Loading..", "Analyzing Text", true, false);
}
protected Void doInBackground(String... strings) {
String language = strings[0].toLowerCase();
String the_text = strings[1];
Socket socket = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
socket = new Socket(my_ip, port);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
dos.writeUTF(language+"****"+the_text);
String in = "";
while (in.indexOf("</content>") < 0) {
in += dis.readUTF();
}
socket.close();
save_str(OUTPUT_KEY, in);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute() {
if (dialog.isShowing())
dialog.dismiss();
startActivity(new Intent (output_intent));
}
}
The recommended way in Android is to use one of the two included HttpClients:
Apache HTTP Client
HttpURLConnection
There is no need to use sockets directly. These clients do a lot to improve your experience.
Here is a blog article by the Android developers, that explain the basics: http://android-developers.blogspot.de/2011/09/androids-http-clients.html
Related
Good day.Im trying to connect to server with socket.Here is my code on how i do it.
private class SocketConnection extends AsyncTask<String, String, String> {
PrintWriter out;
BufferedReader in;
#Override
protected String doInBackground(String... params) {
connect();
try {
out = new PrintWriter(clientSocket.getOutputStream());
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException ex) {
System.out.append("error").append("socketcoonection").println();
}
String msg = null;
try {
msg = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (run) {
System.out.append(msg).append("socketcoonection").println();
out.println();
out.flush();
/*try {
msg = in.readLine();
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}*/
}
return null;
}
}
and here is the connect() method
public void connect() {
try {
clientSocket = new Socket("vaenterprises.org/test.php", 8080);
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
if (clientSocket != null) {
run = true;
}
}
and this is the server side php code of test.php
echo json_encode("socket working");
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
and the address link is vaenterprises.org/test/php so im trying to connect to it and read the input or output stream or the echo.Whatever i do,i get nullPointerException at System.out.append(msg).append("socketcoonection").println(); and during debug i figured out that its socket which is null...Please tell me what am i doing wrong?
I am developing a android wifi -chat application .
Bit of Info about my app :
->A device calls startserver() to act as a server ,another device calls start client() to act as a client
What works:
->A Client can successfully send the data for the first time to the client, but not again and again
->I need to call startserver() again on first device , so that client can send data again .
The startserver() calls this Async task ,the following is its DoinBackgroundMethod
protected String doInBackground(Void... params) {
ServerSocket serverSocket = null;
try {
while(true) {
serverSocket = new ServerSocket(PORT);
Socket client = serverSocket.accept();
StartMSG(client);
}
} catch (IOException e) {
return null;
} finally {
try {
chatclient.changeserverrunning(false);
if (serverSocket == null) {
} else {
serverSocket.close();
}
return null;
} catch (Exception e) {
}
}
//return null;
}
protected void StartMSG(Socket client){
try {
InputStream inputstream = client.getInputStream();
ObjectInputStream ois = new ObjectInputStream(inputstream);
Message m = null;
try {
m = (Message) ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (m != null) {
if (m.gettype() == 1) {
final String my_msg = m.getMessage();//Toast msg afterwards
}
}catch (Exception e){
}
}
Client Side Code :
It is started when the client hits send button and calls start client method .in which It sets up the Ip values before and bundles them and calls the message sending part as a Intent Service called FileTransferService
Its code is (abstracted) :
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if(socket==null){
socket = new Socket();
}
if (intent.getAction().equals(ACTION_SEND_FILE)) {
final String msg_type=intent.getExtras().getString(MESSAGE_TYPE);
String host = intent.getExtras().getString(EXTRAS_ADDRESS);
int port = intent.getExtras().getInt(EXTRAS_PORT);
try {
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Message m = (Message) intent.getExtras().getSerializable(MESSAGE_INTENT_STR);
final String my_message=m.getMessage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(m);
oos.flush();
oos.close();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
OutputStream stream = socket.getOutputStream();
ChatClient.copyFile(is, stream);
} catch (IOException e) {
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
//socket.close();
} catch (Exception e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
You should try https://github.com/tavendo/AutobahnAndroid and run the client from a service, from an asyntask it will always end up finishing.
I am trying to implement a simple socket that sends and receives strings from a server.
The following code is freezing the application, not sure if I have done something obviously wrong?
public String internetRoutesRetrieve(String userName) {
String command = null;
String response = null;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("Hidden IP", HiddenPort);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
command = "SEARCH <" + userName + ">";
dataOutputStream.writeUTF(command);
response = dataInputStream.readUTF();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (socket != null) {
try {
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();
}
}
}
return response;
}
Thanks
Edit: It seems the program is freezing when I am trying to save the response from the server
see AsyncTask for proper client server communication on Android application.
you'd usualy get android.os.NetworkOnMainThreadException if you don't but I'd give it a try.
i've done an application in which the android application send datas to java desktop swing application as well as send datas from desktop to android using TCP socket programming through wifi.
Th application is a Hotel Kitchen order booking system
The problem describes that Dine_Tables class contains buttons which represents each tables in a hotel, on clicking table1 button for example it starts the BackgroundServers Asyntask which runs a server for receiving desktop application datas also it takes the activity from Dinein_Tables.java to Food_Customizer.java.
In Food_Customizer.java on clicking submit button it starts ServersendAsyncAction Asyntask which sends some datas to desktop swing application.
The desktop application after processing sends some datas to android application, The server that runs in the android application on receiving the datas goes again from Food_Customizer.java to Dinein_Tables.java activity in the BackgroundServers Asyntask onPostExecute method.
The problem is that when i do this process a two or three times the application stop due to address-in use and Null-Pointer exception at socket = serverSocket.accept(); in the BackgroundServers Asyntask.
Can anyone please tell me some solution for this problem
Dinein_Tables.java
public class Dinein_Tables extends Activity {
:
:
table1.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
Food_Customizer.BackgroundServers ob = new Food_Customizer().new BackgroundServers(contexts);
ob.execute("");
Intent toAnotherActivity = new Intent(v.getContext(), Food_Customizer.class);
startActivity(toAnotherActivity);
finish();
}
}, 100L);
}
});
}
Food_Customizer.java
public class Food_Customizer extends Activity {
:
:
submit= (Button)findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pd = ProgressDialog.show(contexts, "Sending to Server...","Please Wait...", true, false);
new ServersendAsyncAction().execute();
}
});
:
:
/****************************** AsyncTask ********************************************************/
private class ServersendAsyncAction extends AsyncTask<String, Void, String> {
/****************************** AsyncTask doInBackground() ACTION ********************************/
protected String doInBackground(String... args) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
boolean flag = true;
while (flag) /******** If data is send flag turn to be false *******/
{
try {
socket = new Socket("192.168.1.74", 4444);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(datastosend);
flag = false;
} catch (UnknownHostException e) {
flag = true;
e.printStackTrace();
} catch (IOException e) {
flag = true;
e.printStackTrace();
}
/******** CLOSING SOCKET *****************/
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/******** CLOSING DATAOUTPUTSTREAM *******/
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/******** CLOSING DATAINPUTSTREAM ********/
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
/******** returns what you want to pass to the onPostExecute() *******/
}
/****************************** AsyncTask onPostExecute() ACTION *********************************/
protected void onPostExecute(String result) {
}
/********************* ENDING OF ASYN TASK CLASS ServersendAsyncAction ***************************/
}
public Context con;
public static ServerSocket serverSocket = null;
public class BackgroundServers extends AsyncTask<String, Void, String> {
public BackgroundServers(Context context) {
con=context;
}
/****************************** AsyncTask doInBackground() ACTION ********************************/
protected String doInBackground(String... args) {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(9999);
System.out.println("Listening :9999");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
String incoming_message=(dataInputStream.readUTF());
incoming_message=incoming_message.replace("/", "");
String recdatas[]=incoming_message.split("#");
if(recdatas[0].equalsIgnoreCase("success"))
{
DatabaseConnection dbs=new DatabaseConnection(con);
int status=dbs.update("UPDATE hotel_pub_tables SET status='occupied' WHERE tableno='"+recdatas[1]+"'");
if(status>0)
{
tabelstatus=1;
//msg.obj="Table status changed!!!";
System.out.println("Table status changed!!!");
if (true) {
System.out.println("entered 222");
System.out.println(tabelstatus);
if(tabelstatus==1)
{
System.out.println(tabelstatus);
Food_Customizer.pd.dismiss();
System.out.println("success");
}
else if(tabelstatus==2)
{
Food_Customizer.pd.dismiss();
Intent intent = new Intent(Food_Customizer.this, Dinein_Tables.class);
startActivity(intent);
finish();
}
}
}
else
tabelstatus=2;
dbs.close();
}
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/******** returns what you want to pass to the onPostExecute() *******/
}
/****************************** AsyncTask onPostExecute() ACTION *********************************/
#Override
protected void onPostExecute(String result) {
System.out.println("eneterd on posttttttttttttttt");
con.startActivity(new Intent(con, Dinein_Tables.class));
finish();
}
}
}
/********************* ENDING OF ASYN TASK CLASS BackgroundServers ***************************/
}
Well it's obvious that you setup your server on port 9999:
serverSocket = new ServerSocket(9999);
But you connect with the server on port 4444:
socket = new Socket("192.168.1.74", 4444);
Make sure you connect to the correct port-number otherwise it wont work. Hope this helps.
I have a BufferedReader, when I try to read it, it just hangs and doesn't do anything, am I doing this right? I am using this in an AsyncTask.
Edit: I have a tablet connected to the Wi-Fi, this connects to my computer which is broadcasting on 172.20.104.203 on port 5334, I can see when the thread starts, but nothing after that.
Here my code:
try {
final BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
final String msg;
msg = (line);
Log.d("DeviceActivity", msg);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ClientAcivtity: Exception",
String.valueOf(e));
}
EDIT
I have all the right permissions or anything, I was doing this outside a AsyncTask and it worked perfectly, moved it because I didn't want it in the main thread.
-Edit , here is the full code.
public class NetworkTask extends AsyncTask<Void, byte[], Boolean> {
Socket nsocket; // Network Socket
InputStream nis; // Network Input Stream
OutputStream nos; // Network Output Stream
private Handler handler = new Handler();
Boolean connected = false;
public static final int PORT = 5334;
public String SERVERIP = "172.20.104.203";
Socket socket;
#Override
protected void onPreExecute() {
Log.i("AsyncTask", "onPreExecute");
InetAddress serverAddr;
try {
serverAddr = InetAddress.getByName(SERVERIP);
socket = new Socket(serverAddr, PORT);
connected = true;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ClientAcivtity: Exception", String.valueOf(e));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ClientAcivtity: Exception", String.valueOf(e));
}
}
#Override
protected Boolean doInBackground(Void... params) { // This runs on a
// different thread
boolean result = false;
try {
Log.d("ClientActivity", "C: Connecting...");
if (socket != null) {
int cont = 1;
while (cont == 1) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
// where you issue the commands
out.println("getPos");
Log.d("ClientActivity", "C: Sent " + "getPos");
} catch (Exception e) {
Log.e("ClientAcivtity: Exception",
String.valueOf(e));
}
try {
final BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
final String msg;
msg = (line);
Log.d("DeviceActivity", msg);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ClientAcivtity: Exception",
String.valueOf(e));
}
cont--;
}
Log.d("ClientActivity", "C: Closed.");
}
} catch (Exception e) {
Log.e("ClientAcivtity: Exception", String.valueOf(e));
}
return result;
}
#Override
protected void onProgressUpdate(byte[]... values) {
if (values.length > 0) {
Log.i("AsyncTask", "onProgressUpdate: " + values[0].length
+ " bytes received.");
}
}
#Override
protected void onCancelled() {
Log.i("AsyncTask", "Cancelled.");
}
#Override
protected void onPostExecute(Boolean result) {
if (socket != null) {
if (connected) {
if (result) {
Log.i("AsyncTask",
"onPostExecute: Completed with an Error.");
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.i("AsyncTask", "onPostExecute: Completed.");
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
My guess is that when you write out the command "getPos" the underlying BufferedWriter is not actually sending the data out on the line (you should verify this with tcpdump/wireshark). If this is the case, the server doesn't responsed to the readLine(), since it never got a command. To verify this claim, add out.flush(); after out.println("getPos");
Really, tcpdump will probably give you a better answer then anyone on the forums.
Also see http://developer.android.com/reference/java/io/BufferedWriter.html
Try doing it like this:
final BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
StringBuffer buf = new StringBuffer();
int i;
while((i = in.read()) != -1){
buf.append((char) i);
}
String data = buf.toString();
Reading from sockets is a quite difficult issue depending where the socket is actually connected to and how the other side responds.
If the other side is extremely fast than it can provide the socket with enough data so that the read routines actually work fine. However if there is a delay in the other side of any kind (just needs to be slower than your read routine incl the small default timeout) then your read fails even though there might be data on the other side - just arriving a little too slow at the socket.
Depending on your needs you may wrap your own minimum and maximum timer around the read routine.
Please provide more information and we can better understand the issue.
In many cases it is necessary to have a minimum timeout large enough for the other side to push data to the socket - but you might also need a maximum time for how long you actually want to wait for data to arrive.
UPDATE:
first the runnable to start the monitoring thread. You may use monitoringCanRun in your loop to interrupt the thread if required. And monitoringThreadIsAlive can be used to know if the thread is still running.
monitoringCanRun = true;
new Thread(new Runnable() {
public void run() {
monitoringThreadIsAlive = true;
performMonitoring();
monitoringThreadIsAlive = false;
}
}).start();
}
and performMonitoring looks like:
public void performMonitoring() {
while (monitoringCanRun) {
... do your read in the while loop
...you might like to insert some delay before trying again...
try { //we delay every partial read so we are not too fast for the other side
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}