0
我創建了一個應用程序連接到一個java實現的服務器,連接到一個mysql數據庫,從服務器端一切正常,在android每次我連接到服務器我可以發送消息,但當閱讀響應套接字被關閉時,我認爲問題來自虛擬機,殺死線程,我google'it並嘗試運行套接字類作爲一個活動後,作爲一個線程,我甚至嘗試給線程優先,但我總是得到同樣的錯誤:由VM殺死Android客戶端套接字
12-28 18:28:24.769: W/System.err(1342): java.net.SocketException: Socket closed
12-28 18:28:24.769: W/System.err(1342): at org.apache.harmony.luni.platform.OSNetworkSystem.read(Native Method)
12-28 18:28:24.769: W/System.err(1342): at dalvik.system.BlockGuard$WrappedNetworkSystem.read(BlockGuard.java:273)
12-28 18:28:24.769: W/System.err(1342): at org.apache.harmony.luni.net.PlainSocketImpl.read(PlainSocketImpl.java:458)
12-28 18:28:24.769: W/System.err(1342): at org.apache.harmony.luni.net.SocketInputStream.read(SocketInputStream.java:59)
12-28 18:28:24.769: W/System.err(1342): at java.io.DataInputStream.readLine(DataInputStream.java:310)
12-28 18:28:24.769: W/System.err(1342): at com.example.lightreading.ConnectionDB$clientCon.run(ConnectionDB.java:83)
12-28 18:28:24.769: W/System.err(1342): at java.lang.Thread.run(Thread.java:1019)
下面是一個使用線程我的代碼:
public class ConnectionDB{
public static String ip;
public static int port;
private static ConnectionDB instance = null;
private StringBuilder sb;
private String response = "";
private String data;
public static ConnectionDB getInstance() {
if(instance == null) {
instance = new ConnectionDB();
}
return instance;
}
public String connect(String s_send) throws InterruptedException{
data = s_send;
Thread cThread = new Thread(new clientCon());
cThread.setPriority(Thread.MAX_PRIORITY);
cThread.start();
return response.toString();
}
class clientCon implements Runnable {
private Socket socket = null;
private DataOutputStream dataOutputStream = null;
private DataInputStream dataInputStream = null;
@Override
public void run() {
// TODO Auto-generated method stub
try {
socket = new Socket(ip,port);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
Log.d("sending msg: ",data);
dataOutputStream.writeBytes(data);
dataOutputStream.flush();
dataOutputStream.close();
Log.d("msg sent: ", data);
while ((data = dataInputStream.readLine()) != null) {
Log.d("data from server: ", data);
sb.append(data);
}
Log.d("msg received: ", sb.toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (sb != null){
response = sb.toString();
Log.d("Response from server: ", response);
}else{
Log.d("Response from server is null", "");
}
}
}
}