写的一个简单的测试,android手机客户端向服务器发送一个字符串,服务器接收到字符串后,把字符串加工,再返回到客户端,
在客户端用TextView控件将获取的打印出来。。。我是想用多线程来实现的
这是android客户端的代码
- Java code
package cn.bzu.edu.Thread;import android.app.Activity;import android.graphics.Canvas;import android.os.Bundle;import android.widget.TextView;public class THREAD_1_ACTIVITY extends Activity { /** Called when the activity is first created. */ int x=1; TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv=(TextView)findViewById(R.id.myTextview); AndroidThread thread=new AndroidThread(tv); } }//AndroidThread类package cn.bzu.edu.Thread;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.InetAddress;import java.net.InetSocketAddress;import java.net.Socket;import java.net.UnknownHostException;import android.widget.TextView;public class AndroidThread implements Runnable { TextView myTextView; Socket socket; DataInputStream dis=null; DataOutputStream dos=null; public AndroidThread(TextView tv) { // TODO Auto-generated constructor stub myTextView = tv; Thread thread=new Thread(this); socket=new Socket(); try { InetAddress address=InetAddress.getByName("10.3.5.136"); InetSocketAddress socketAddress=new InetSocketAddress(address,6666); socket.connect(socketAddress); dis=new DataInputStream(socket.getInputStream()); dos=new DataOutputStream(socket.getOutputStream()); } catch (UnknownHostException e) { tv.setText("socket"); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } thread.start(); } @Override public void run() { // TODO Auto-generated method stub String s; try { //myTextView.setText("execute run method()"); if(socket.isConnected()){ if(socket!=null){ dos.writeUTF("POST"); myTextView.setText("post"); s=dis.readUTF(); myTextView.setText(s); }else { myTextView.setText("socket is null"); } }else { myTextView.setText("socket NOT CONNECTION"); } } catch (Exception e) { // TODO Auto-generated catch block } }}
这个可以把post发送给服务器,服务器端也能显示,但是就是感觉在dis.writeUTF()那地方有误,我试着用if(dis.writeUTF==null)进行一下判断,结果好像这句根本就不执行,整个程序到dis.writeUTF()就断了,希望高手能够给小弟解决一下。。
------解决方案--------------------------------------------------------
没做过android,帮顶
------解决方案--------------------------------------------------------
我也是这个问题··不知道怎么弄····郁闷·大哥·你弄出来了··给我说说···
------解决方案--------------------------------------------------------
代码没什么大问题,
能跑,
如果有问题,可能是Server写得不好。
------解决方案--------------------------------------------------------
先writeutf注释掉,你自己看看发的上下文,命的什么名,自己都搞反了