【发布时间】:2018-06-25 17:52:15
【问题描述】:
我正在尝试使用套接字将命令从我的手机发送到我的计算机。 我在这里尝试了答案: Android and PC Socket connection
但经过一番挖掘后,我发现您需要使用异步任务,所以我尝试了这个: Using AsyncTask for android network connection
但由于某种原因,我的套接字超时。有没有办法找出原因?因为从错误中我无法判断:
这是客户端代码:
public class MainActivity extends AppCompatActivity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String message;
private static final int SERVERPORT = ####;
private static final String SERVER_IP = "########";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText1); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
}
public void onClick(View view) {
message = textField.getText().toString();
textField.setText(""); // Reset the text field to blank
new AsyncAction().execute();
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
System.out.println("background running");
System.out.println(message);
client = new Socket(SERVER_IP, SERVERPORT); // connect to server
System.out.println(client.isConnected());
System.out.println("test");
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(message); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
【问题讨论】:
-
你在 catch 块中什么都不做。返回带有错误消息和 e.getMessage() 的字符串。在 onPostExecute() 中显示带有 Toast 的字符串。然后您的应用的用户就会知道会发生什么。