android - 我的客户端将连接到服务器,仅此而已

标签 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){}
}

最佳答案

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

关于android - 我的客户端将连接到服务器,仅此而已,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9548321/

相关文章:

java - 当构造函数在牙签中有参数时通过工厂注入(inject)

android - 在 android 中加入表格

c# - 通过 WCF 提供整个库的功能

java - 将 Byte[] append 到二进制文件的末尾

android - 在启动您的应用程序时关闭设备音乐

使用fifos的客户端服务器,发送突发和接收处理时间

client - Luci(Openwrt)无线网桥客户端-如何配置?

java - 在 Java 中使用 Double 值序列化和反序列化数据

java - DataOutputStream 的 writeDouble() 方法以编码形式将数据写入文本文档

java - 在 Android 上开始和结束一周