【问题标题】:failure in creating the client socket创建客户端套接字失败
【发布时间】:2011-04-10 02:58:11
【问题描述】:

我正在尝试在 android 中连接两个模拟器,一个被认为是服务器,一个被认为是客户端。 我使用文本视图和处理程序来发布客户端和服务器的状态。 我的客户端的问题是我可以创建套接字,通常我会在文本视图上发布一条错误消息。不仅如此,当我尝试按下客户端应用程序上的按钮时,我会强制关闭,但我没有不知道为什么我有一个不同的线程用于客户端的连接:)

谁能告诉我我做错了什么?

这是我的代码:

公共类 screen1 扩展 Activity {

private TextView clientState;
private String serverIpAddress="10.0.2.2";
public static final int ClientPort = 8080;
private boolean connected = false;
private Handler handler=new Handler();
Socket socket;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.screen1);
    clientState = (TextView) findViewById(R.id.client_Status);

    Button b = (Button)findViewById(R.id.mainMenu);
    b.setOnClickListener(new View.OnClickListener() {
       public void onClick(View arg0) {
       Intent i = new Intent(screen1.this, screen2.class);
       startActivity(i);
       } 
    });

   Thread cThread=new Thread(new ClientThread()); 
  cThread.start();  
  }
public class ClientThread implements Runnable{
    public void run()
    {
        try
        {
            InetAddress serverAddr=InetAddress.getByName(serverIpAddress);
            handler.post(new Runnable(){
                public void run(){
                    clientState.setText(" try to connect!");
                }
            });
            socket=new Socket(serverAddr,ClientPort);

            handler.post(new Runnable(){
                public void run(){
                    clientState.setText("Connected!");
                }
            });

        }
        catch(Exception e){
            handler.post(new Runnable(){
                public void run(){
                    clientState.setText("Error");
                    }
            });

            e.printStackTrace();
        }

    }
}
protected void onStop() {
    super.onStop();
    try {
         // make sure you close the socket upon exiting
         socket.close();
     } catch (IOException e) {
         e.printStackTrace();
     }
}

}

【问题讨论】:

    标签: android sockets client


    【解决方案1】:

    我不擅长 Android 编程,但我看到您在代码中进入了无限循环:

    while(true){
            handler.post(new Runnable(){
                public void run(){
                    clientState.setText("Connected!");
                }
            });
            }
    

    【讨论】:

    • 嗯,这是一个普通的 TCP/IP 连接,不得不说当你尝试连接到模拟器时有点不同,但是是的......在我创建套接字后,绑定它并连接到本地主机我有这个循环......这可能是一个问题,但我的程序只有
    • 这里:public void run(){ clientState.setText("尝试连接!"); }
    • 在我所说的文本视图中,我有“尝试连接”,我从来没有得到“连接”,所以我猜它永远不会进入循环。谢谢你:)
    • 你能把while改成if吗?由于您正在执行无限循环,因此可能会遇到 OutOfMemoryException。
    • 我删除了while循环,反正我不需要它,但它仍然不显示连接,我可以找出问题所在:-S
    猜你喜欢
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 2014-10-28
    • 2018-01-06
    • 1970-01-01
    • 2019-02-07
    相关资源
    最近更新 更多