我需要使用tcp套接字连接来获取蓝盒中的数据,如果我输入注释,例如“getcolor”,蓝盒会向我发送“红色,蓝色”等信息。 在这种情况下,bluebox作为服务器,我不需要对它进行编程,但是我有问题在EditText上显示信息。
public class sender {
public static void main(String[] args)throws IOException{
Socket socket = new Socket("192.168.1.176",14111);
OutputStream out = socket.getOutputStream();
BufferedReader msg = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter ou = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)),true);
String buffer = new String("");
String ms = "";
while(true)
{
while(in.ready())
buffer+= in.readLine()+ "\n";
String[] line = buffer.split("\n");
while(msg.ready())
ms = msg.readLine();
if(ms.equals("exit"))
{
break;
}
if(!ms.equals(""))
{
ou.println(ms);
ou.flush();
ms = "";
}
if(!buffer.equals(""))
{
System.out.print(buffer);
buffer = "";
}
}
in.close();
out.close();
socket.close();
}
}
这个java代码有效,但在下面的android代码中失败了:
public class BlueBoxApp extends Activity {
/** Called when the activity is first created. */
Context appInstance = this;
private EditText info;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
info = (EditText)findViewById(R.id.EditText01);
try{
InetAddress serverAddr = InetAddress.getByName("192.168.1.176");//TCP服务器IP地址
Log.d("TCP", "server,receiving...");
Socket socket = new Socket(serverAddr,14111);
try {
OutputStream out = socket.getOutputStream();
BufferedReader msg = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter ou = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)),true);
String buffer = new String("");
String ms = "getsensorno";
Log.d("TCP", "sending:'"+ms+"'");
while(true)
{
while(in.ready())
buffer+= in.readLine()+ "\n";
while(msg.ready())
ms = msg.readLine();
if(ms.equals("exit"))
{
break;
}
if(!ms.equals(""))
{
ou.println(ms);
ou.flush();
ms = "";
}
if(!buffer.equals(""))
{
info.setText(buffer);
buffer = "";
}
}
} catch (Exception e) {
Log.e("TCP", "error",e);
}finally{
socket.close();
}
}catch(Exception e){
Log.e("TCP", "error",e);
}
}
}
问题是什么以及如何为它设置线程?谢谢!
答案 0 :(得分:3)
正如您所指出的,问题在于您正在主线程上执行网络部分。
设置新线程很简单,请考虑使用AsyncTask。在开始实现它之前,请阅读文档(这是非常好的),这将使恕我直言更容易。
另外,请确保您在 AndroidManifest.xml
中拥有互联网权限