似乎当我使用 Socket 类的accept方法时,整个程序都会卡住,直到数据通过。我已将套接字传递给一个线程,它不会卡住,但我需要该线程返回数据,但我认为它无法做到这一点。
获取用户名的代码
public boolean checkUsername() {
NetworkIO n = new NetworkIO();
// Grabs username from edittext field
username = usernameEditText.getText().toString();
System.out.println(usernameEditText.getText().toString());
// queries databse for username
try {
resultFromServer = n.query("username",
"select username FROM user_info WHERE MATCH (username) AGAINST ('"
+ username + "' IN NATURAL LANGUAGE MODE);");
} catch (IOException e) {
e.printStackTrace();
}
}
NetworkIO 类代码
public class NetworkIO extends Activity {
Socket networkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
public String query(String request, String fieldRequested)
throws IOException {
// Tries to get connection
try {
networkSocket = new Socket("192.168.1.8", 9009);
out = new PrintWriter(networkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
networkSocket.getInputStream()));
System.out.println("Hi from in made");
} catch (UnknownHostException e) {
System.err.println("Unknown host");
System.exit(-1);
} catch (IOException e) {
System.err.println("IOException");
System.exit(-1);
}
//Sends Request
out.println(request);
out.println(fieldRequested);
String resultFromServer = "";
//Waits for response and if its null exit
while ((in.readLine()) != null) {
resultFromServer += in.readLine();
}
System.out.println(resultFromServer);
//Close the connections
out.close();
in.close();
networkSocket.close();
return resultFromServer;
}
}
对我的代码的任何批评将不胜感激:)
最佳答案
通常的模式是在线程内运行接受循环,并有一个单独的处理程序线程池,您可以将请求分派(dispatch)到其中。
当你从accept得到一个新的socket时,将这个socket交给一个工作线程来处理。这样您就不需要将任何内容传递回主线程。
示例直接来自 ExecutorService javadocs:http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
关于java - 如何使用套接字进行线程以便程序不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6784629/