UnknownHostException causes Fatal error in AsyncTask - android

I have the following code, and all works fine when I can connect to the server:
public void getXMLData()
{
if (skipUpdate)
{
skipUpdate=false;
return;
}
skipUpdate=true;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int SERVERPORT=0;
try {
SERVERPORT = Integer.parseInt(prefs.getString("pref_key_port_1","Port"));
} catch (NumberFormatException e) {
txtStatus.setText("Invalid Port Number");
return;
}
String SERVERHOST = prefs.getString("pref_key_host_1","127.0.0.1");
String PASSWORD = prefs.getString("pref_key_pass_1", "password");
try {
XMLFetcherTask myXMLFetcherTask = new XMLFetcherTask(SERVERHOST,SERVERPORT,PASSWORD);
myXMLFetcherTask.execute();
} catch (Exception e) {
txtStatus.setText("Error "+e.getMessage());
return;
}
skipUpdate=false;
}
public class XMLFetcherTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String password="";
XMLFetcherTask(String addr, int port, String pass){
dstAddress = addr;
dstPort = port;
password=pass;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(password);
response="";
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (response.toLowerCase().indexOf("</response>")<0)
{
response+=input.readLine();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtStatus.setText("UnknownHostException: " + e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtStatus.setText("IOException: " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtStatus.setText("Exception: " + e.getMessage());
} finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//txtStatus.setText("Exception Finally: " + e.getMessage());
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if( !(response.substring(0,5).equalsIgnoreCase("<resp") || response.substring(0,5).equalsIgnoreCase("<?xml")) ) //!response.substring(0,5).equalsIgnoreCase("<?xml") ||
{
txtStatus.setText("Server response doesn't look XML, please check password: '"+response.substring(0,5)+"'");
} else {
lastXMLData=response;
txtStatus.setText("Resp Len: " + response.length());
skipUpdate=false;
updateFragmentListeners();
}
super.onPostExecute(result);
}
}
Now, when I get UnknownHostException, the app force close with following stack trace:
07-29 15:52:08.754 1525-1538/android.process.acore V/BackupServiceBinder﹕ doBackup() invoked
07-29 15:52:08.766 1525-1538/android.process.acore E/DictionaryBackupAgent﹕ Couldn't read from the cursor
07-29 16:29:55.178 1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:71)
at android.os.Binder.execTransact(Binder.java:446)
07-29 16:29:55.178 1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:64)
at android.os.Binder.execTransact(Binder.java:446)
07-29 16:29:55.178 1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:57)
at android.os.Binder.execTransact(Binder.java:446)
I have no idea why this happen...
I tried to comment hte txtStatus.setText as normally it's not supposed to work from another thread, but no change.
Tested on android emulator with framework 22 and on my phone with framework 21.
Any idea would be welcome

Ok I manage to make it work using threads instead, here's final code:
public void getXMLData()
{
if (skipUpdate)
{
skipUpdate=false;
return;
}
skipUpdate=true;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int SERVERPORT=0;
try {
SERVERPORT = Integer.parseInt(prefs.getString("pref_key_port_1","Port"));
} catch (NumberFormatException e) {
txtStatus.setText("Invalid Port Number");
return;
}
String SERVERHOST = prefs.getString("pref_key_host_1","127.0.0.1");
String PASSWORD = prefs.getString("pref_key_pass_1", "password");
try {
// XMLFetcherTask myXMLFetcherTask = new XMLFetcherTask(SERVERHOST,SERVERPORT,PASSWORD);
// myXMLFetcherTask.execute();
XMLFetcherTask XMLFetcherTaskThread = new XMLFetcherTask();
XMLFetcherTaskThread.dstAddress=SERVERHOST;
XMLFetcherTaskThread.dstPort=SERVERPORT;
XMLFetcherTaskThread.password=PASSWORD;
Thread cThread = new Thread(XMLFetcherTaskThread);
cThread.start();
} catch (Exception e) {
txtStatus.setText("Error "+e.getMessage());
return;
}
skipUpdate=false;
}
public class XMLFetcherTask implements Runnable {
String dstAddress;
int dstPort;
String response = "";
String password="";
private void setStatusFromThread(final String status)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
setStatus(status);
}
});
}
private void updateListenersThread()
{
runOnUiThread(new Runnable() {
#Override
public void run() {
updateFragmentListeners();
}
});
}
public void run() {
Socket socket = null;
//BufferedReader input = null;
//PrintWriter out = null;
try {
socket = new Socket(dstAddress, dstPort);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(password);
response="";
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (response.toLowerCase().indexOf("</response>") < 0) {
response+=input.readLine();
}
if( !(response.substring(0,5).equalsIgnoreCase("<resp") || response.substring(0,5).equalsIgnoreCase("<?xml")) ) //!response.substring(0,5).equalsIgnoreCase("<?xml") ||
{
setStatusFromThread("Server response doesn't look XML, please check password: '" + response.substring(0, 5) + "'");
} else {
lastXMLData=response;
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
setStatusFromThread("Last update: " + ft.format(dNow));
skipUpdate=false;
updateListenersThread();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
setStatusFromThread("UnknownHostException: " + e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
setStatusFromThread("IOException: " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
setStatusFromThread("Exception: " + e.getMessage());
} finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//txtStatus.setText("Exception Finally: " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
}
}

Related

Chat along with another data sending in socket programming android

I'm developing a project where client sends screenshots of its activity to server where the bitmap is converted to string.For me it works well.I would like to add a chat between client and server in this project.How can I achieve this?Any kind of help is accepted.
Client Code
public class Client2 extends AsyncTask<Void, Void, Void> {
public static String dstAddress;
int dstPort;
String response= new String() ;
String msg_server=new String();
Context context;
public static ArrayList<Bitmap>ss=new ArrayList<>();
public static Socket socket;
Client2(Context ic,String addr, int port,String msg) {
context=ic;
dstAddress = addr;
dstPort = port;
msg_server=msg;
}
#Override
protected Void doInBackground(Void... arg0) {
socket = null;
ObjectOutputStream dataOutputStream = null;
ObjectInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
dataInputStream = new ObjectInputStream(socket.getInputStream());
if(msg_server != null){
dataOutputStream.writeObject(msg_server);
dataOutputStream.flush();
}
response = (String) dataInputStream.readObject();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} 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();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
}}
Server Code
public class Server extends Thread{
ServerSocket serverSocket;
Viewer activity;
static final int SocketServerPORT = 8080;
int count = 0;
int sc=0;
Bitmap bmviewer;
String msgtoclient,msgfromclient;
ArrayList<Bitmap>ser=new ArrayList<>();
public Server(Activity context,String msg )
{
activity= (Viewer) context;
msgtoclient=msg;
}
#Override
public void run() {
Socket socket = null;
ObjectInputStream dataInputStream = null;
ObjectOutputStream dataOutputStream = null;
try {
// serverSocket = new ServerSocket(SocketServerPORT);
serverSocket = new ServerSocket(); // <-- create an unbound socket first
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(SocketServerPORT));// serverSocket.setReuseAddress(true);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Viewer.demo.setText("Port No: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new ObjectInputStream(
socket.getInputStream());
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
String messageFromClient = new String();
//If no message sent from client, this code will block the program
messageFromClient = (String) dataInputStream.readObject();
count++;
bmviewer = (stringtobitmap(messageFromClient));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Viewer.demo.setText(message);
sc++;
saveimage(bmviewer, sc);
// Viewer.images.setImageBitmap(bmviewer);
Viewer.imageGallery.addView(getImageView(bmviewer));
}
});
if (msgtoclient.equals("")){
String reply="received";
dataOutputStream.writeObject(reply);
dataOutputStream.flush();}
else {
dataOutputStream.writeObject(msgtoclient);
dataOutputStream.flush();
}
}
}catch(EOFException e){
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.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();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private View getImageView(Bitmap image) {
ImageView imageView = new ImageView(activity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 10, 0);
imageView.setLayoutParams(lp);
imageView.setImageBitmap(image);
return imageView;
}
private void saveimage(Bitmap bmp,int c) {
sc=c;
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/screenshare_viewer");
myDir.mkdirs();
//Random generator = new Random();
// int n = 10000;
// n = generator.nextInt(n);
String fname = "Image-"+sc +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap stringtobitmap(String message) {
try{
byte [] encodeByte= Base64.decode(message,Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}
catch(Exception e){
e.getMessage();
return null;
}
}
}

clearing multiple apps' data android

I'm able to clear a single package name's data through this snippet. However, i want it to handle more than one package names. in other words, it should clear two more package names' data
private void clearData() {
//"com.uc.browser.en"
//"pm clear com.sec.android.app.sbrowser"
String cmd = "pm clear com.sec.android.app.sbrowser" ;
ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true)
.command("su");
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// We must handle the result stream in another Thread first
StreamReader stdoutReader = new StreamReader(p.getInputStream(),
CHARSET_NAME);
stdoutReader.start();
out = p.getOutputStream();
try {
out.write((cmd + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = stdoutReader.getResult();
}
}
The ProcessCommandsSU class starts an su process in which to run a list of commands, and provides an interface to deliver the output to an Activity asynchronously. Unlike the example you're following, this class will not block the UI thread. The Activity must implement the OnCommandsReturnListener interface.
public class ProcessCommandsSU extends Thread {
public interface OnCommandsReturnListener {
public void onCommandsReturn(String output);
}
private final Activity activity;
private final String[] cmds;
public ProcessCommandsSU(Activity activity, String[] cmds) {
if(!(activity instanceof OnCommandsReturnListener)) {
throw new IllegalArgumentException(
"Activity must implement OnCommandsReturnListener interface");
}
this.activity = activity;
this.cmds = cmds;
}
public void run() {
try {
final Process process = new ProcessBuilder()
.redirectErrorStream(true)
.command("su")
.start();
final OutputStream os = process.getOutputStream();
final CountDownLatch latch = new CountDownLatch(1);
final OutputReader or = new OutputReader(process.getInputStream(), latch);
or.start();
for (int i = 0; i < cmds.length; i++) {
os.write((cmds[i] + "\n").getBytes());
}
os.write(("exit\n").getBytes());
os.flush();
process.waitFor();
latch.await();
process.destroy();
final String output = or.getOutput();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
((OnCommandsReturnListener) activity).onCommandsReturn(output);
}
}
);
}
catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private class OutputReader extends Thread {
private final InputStream is;
private final StringBuilder sb = new StringBuilder();
private final CountDownLatch latch;
public OutputReader(InputStream is, CountDownLatch latch) {
this.is = is;
this.latch = latch;
}
public String getOutput() {
return sb.toString();
}
public void run() {
try {
final BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
e.printStackTrace();
}
latch.countDown();
}
}
}
Using the class is quite simple. We first ensure that our Activity implements the interface. We then create an instance, passing the Activity and our array of commands in the constructor, and call its start() method. In the following example, it's assumed that the Activity has a TextView named textOutput to display the returned output:
public class MainActivity extends Activity
implements ProcessCommandsSU.OnCommandsReturnListener {
...
#Override
public void onCommandsReturn(String output) {
textOutput.append(output + "\n");
}
private void runCommands() {
final String[] cmds = {
"ping -c 5 www.google.com",
"pm list packages android",
"chdir " + Environment.getExternalStorageDirectory(),
"ls"
};
new ProcessCommandsSU(MainActivity.this, cmds).start();
}
}
My device is not rooted, so this was tested with the commands you see in the code above. Simply replace those commands with your pm clear commands.

App not responding while transfer data

I am sending image using Socket Server and Client. It gived me dialog "App not responding" i think beacuse converting this bitmap was making in UiThread. So i tried to change it but i am still getting this message "App is not responding". It's happening when i am sending big imaes +500kb.
Here is my code for Server:
public class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
while (true) {
Socket socket = serverSocket.accept();
count++;
// Here where i am doing my code i think is not doing in UiThread..
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run()
{
// Firstly i was doing my code here...
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My code for client:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try
{
//I am sending my image here...
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
}
So please help my . Why still i am getting not responding dialog?
The ANR error code happens when you block the UI thread more than 5 seconds. If you need to do background work don't use the main thread. Receive the data in a separate thread and post only the result to the UI thread.

Android Socket: Read Continuous Data

I am trying to read data continuously using the following code:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1){
readInpt = inputStream.toString();
byteArrayOutputStream.write(buffer, 0, bytesRead);
response = byteArrayOutputStream.toString("UTF-8");
}
textResponse.setText(readInpt);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
But for some reason, it doesn't show me any output in the textbox. any help would be appreciated.
There are at least two issues in your code.
Frist, I'm not sure the method toString() on the inputStream is going to work, because the documentation says it returns a description of the object (which would be different than the string recieved). You might be confusing this with the contents of buffer which might be what you really want.
readInpt = inputStream.toString(); // Probably wrong
Second. You're updating the User Interface from a background thread, inside doInBackground() , which is always forbidden.
textResponse.setText(readInpt); // Forbidden, move somewhere else, e.g. onPostExecute()
try {
socket = new Socket(dstAddress, dstPort);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
response = stdIn.readLine();
publishProgress(response);
Log.i("response", response);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
catch (Exception e) {
e.printStackTrace();
}
You cannot print it on text field because the socket will listen to the server socket.If server socket does not send any response it will listen to the socket continuously until the response is received.

Android: Socket is closed

PCClient :
public class PCServer
{
/**
* #param args
*/
static Socket socket = null;
private static String ip = "192.168.42.129";
private static int port = 18181;
public static void main(String[] args)
{
// TODO Auto-generated method stub
try
{
socket = new Socket(ip, port);
} catch (UnknownHostException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
SendMsg(ip, port, "BZT");
GetMessage getMessage = new GetMessage();
getMessage.start();
} catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void SendMsg(String ip, int port, String msg) throws UnknownHostException, IOException
{
try
{
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write(msg);
writer.flush();
writer.close();
//socket.close();
} catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
static class GetMessage extends Thread
{
#Override
public void run()
{
// TODO Auto-generated method stub
super.run();
try
{
while (true)
{
System.out.println("--------------------------------------------------------");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
System.out.println(str);
//client.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
AndroidServer : Service
public class SocketService extends Service
{
public static final int SERVERPORT = 18181;
ServerSocket serverSocket;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// TODO Auto-generated method stub
try
{
serverSocket = new ServerSocket(SERVERPORT);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
GetSocketMessage getSocketMessage = new GetSocketMessage();
getSocketMessage.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
try
{
this.serverSocket.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class GetSocketMessage extends Thread
{
#Override
public void run()
{
// TODO Auto-generated method stub
super.run();
try
{
Log.i("s", "S: Connecting...");
while (true)
{
Socket client = serverSocket.accept();
Log.i("s", "S: Receiving...");
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
Log.i("s", "S: Received: '" + str + "'");
if ("BZT".equals(str))
{
Intent intent = new Intent("com.StarHope.ZWGKXT.connected");
sendBroadcast(intent);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write("OK");
writer.flush();
writer.close();
}
if ( Lbjy_usbActivity.content !=null )
{
Log.i("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "oooooooooooooooooooooooooooooo");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write("");
writer.flush();
writer.close();
}
}
catch (Exception e)
{
Log.i("s", "S: Error");
e.printStackTrace();
}
finally
{
Log.i("s", "S: Done");
}
}
}
catch (Exception e)
{
Log.i("s", "S: Error");
e.printStackTrace();
}
}
}
}
The android phone server can received the message sent from PCClient "BZT",
But when the phone send "OK" to PC , there is always an
Exception:java.net.SocketException: Socket is closed.
How can I fix this?
Closing any stream obtained using getOutputStream() or getInputStream() closes the socket.
Do you receive something before 'BZT' ? If so, the socket will be closed after you sent the empty answer.
You should use only one output stream, and flush() each message without closing.

Categories

Resources