我的客户端将连接到服务器,但就是这样

时间:2012-03-03 17:46:12

标签: android client dataoutputstream

Android客户端将字符串发送到服务器。服务器将确认来自设备的连接,以及正确的端口,但就是它。应该发生的是字符串打印在服务器控制台上。

作为参考,我创建了完全相同的客户端,而不是在Android应用程序中运行它并且它工作正常,所以这让我相信我在android方面缺少一些东西。任何人都可以提出解决此问题的建议。非常感谢。

客户代码:

public class ObjectTestActivity extends Activity {

Button submit;
TextView tv;
private String name = "Hello Android";
private DataOutputStream dos;
private DataInputStream dis;
private final int PORT = 3000;

Button send;
InetAddress host;


@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    send = (Button) findViewById(R.id.send);
    tv = (TextView) findViewById(R.id.tv);


    try{

        host = InetAddress.getLocalHost();
        Socket socket = new Socket("xx.xx.xxx.xxx", PORT);

        dos = new DataOutputStream(socket.getOutputStream());
        dis = new DataInputStream(socket.getInputStream());

    }catch(UnknownHostException e){}
     catch(IOException e){}
}


public void onClick(View view){

    try{
        dos.writeUTF(name);
        dos.flush();
        dis.close();
        dos.close();
    }catch(IOException e){}
}

1 个答案:

答案 0 :(得分:1)

onClick附加什么?尝试更改为:

public class MyActivity extends Activity {

  Button submit;
  TextView tv;
  private String name = "Hello Android";
  private DataOutputStream dos;
  private DataInputStream dis;
  private final int PORT = 3000;

  Button send;
  InetAddress host;

  protected void onCreate(Bundle icicle) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);

        send = (Button) findViewById(R.id.send);
        tv = (TextView) findViewById(R.id.tv);


        try{

            host = InetAddress.getLocalHost();
            Socket socket = new Socket("xx.xx.xxx.xxx", PORT);

            dos = new DataOutputStream(socket.getOutputStream());
            dis = new DataInputStream(socket.getInputStream());

       }catch(UnknownHostException e){}
        catch(IOException e){}


        send.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 try{
                 dos.writeUTF(name);
                 dos.flush();
                 dis.close();
                 dos.close();
              }catch(IOException e){}
             }
         });
     }
 }

对于按钮onClick事件。

简单地说:在onCreate(send.onCreate(...))中定义onClick方法的按钮。

此示例来自here