我正在開發一個應用程序,通過套接字連接以獲取數據,但是一旦我建立了通過按鈕單擊調用的套接字連接,我可以看到我能夠連接並獲取數據,但套接字連接不會終止,並且應用程序掛起。我已經包含了socket.close();在我的代碼,但它是不低於幫助是我的代碼片段..在while循環中不能關閉android的Socket連接
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/// some code which isn't important here
// establish socket connection to get data
try{
Socket s = new Socket("IP",portnumber);
Log.d(TAG, "socket connected");
PrintWriter out1 = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out1.println(value1);
Log.d(TAG, value1);
String line="";
String msg = "";
while ((line=in.readLine()) != "//end of message from server")
{
msg+=line+"\n";
Log.d(TAG, msg);
}
out1.close();
in.close();
s.close();
Log.d(TAG, "socket closed ");
}
catch (IOException e) {
Log.e(TAG, "file finished " + e.getMessage());
}
你試過調試你的代碼嗎? –
yesI確實,當s.close();語句是在while循環中,我得到我的列表中的條目..否則,循環執行,然後程序只是在這段時間內掛起。 – user3747512